So i don't understand how joining of tables works in mysql database
(is it from table that has Primary Key to table that has its Foreign Key? or vice versa?)
I always encounter this and I don't know what is the problem
I have used this sql statement and what I want to achieve is to join three tables then get the result and put it in datagridview and in this code that i do is only two table for me to practice and join 3 tables later on.
string sql = "SELECT category_information.category, description_information.description" +
"FROM category_information INNER JOIN description_information ON category_information.type_id" +
" = description_information.category_information_type_id";
MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near 'INNER JOIN description_information ON
category_information.type_id = description' at line 1'
In C#, the "#" prefixing a string allows you to do multiple lines and can thus cleanly read SQL without extra close-quote + signs. I also changed to utilize table "aliases" for long table names for readability. Just a sample from your original code would directly see readability.
Yet StuardD's answer was correct. When you had the strings concatenated together you would not see the obvious, here you would.
string sql =
#"SELECT
CI.category,
DI.description
FROM
category_information CI
INNER JOIN description_information DI
ON CI.type_id = DI.category_information_type_id ";
Related
I have two access databases, (ProdDB.mdb) and (AllProdOrders.mdb).
In ProdDB.mdb, I have two tables that have the same structure: Data and Archive
In AllProdOrders.mdb, I have one table: Outputs
This is what I want to do:
What I want to do is create an SQL query that will combine the two tables, Data and Archive into one table and remove any duplicates by checking against three columns: Prod Ord, SO nr and Item No. If these three values are the same for any entry, that is a duplicate and thus shouldn't be included.
After this, I want to left join the AllProdOrders.mdb table: Outputs and add a column to the end of my table. This is done by checking the Order Status in that table against the SO nr.
I have already done the left join portion and my query works properly, all I really need to add is combining the two tables and filtering out any duplicates:
This is my code so far...
string sql = "SELECT [Data].[SO nr], [Data].[Value (GBP)], [Data].[Ship Date (Cust)], [Data].[Line] " +
#"FROM [Archive]" +
"UNION " +
#"SELECT [Data].[SO nr], [Data].[Value(GBP)], [Data].[Ship Date(Cust)], [Data].[Line], status.[Order Status] " +
#"FROM [Data] LEFT JOIN [;database=I:\Departments\Production\AllProdOrders.mdb].[Outputs] AS status " +
"ON [Data].[Prod Ord] = status.[No] "
I'm going to use this combination of tables in my query with an OleDBDataReader to get the total (Value (GBP) of certain orders.
I'm getting a number of columns doesn't match error but I'm not sure how to rectify this as the extra column is the Order Status column that is added to the end of the query and comes from the second database.
As you say, you have an extra column in the second part of the union query. The columns must always match in a union-query. If you add ", NULL as [Order Status]" in the end of the first line I believe the error goes away.
I have three tables in MS Access database
users,
rooms,
room_history
room_history contains both users,rooms id. when I try to join users with room_history data successfully retrieve same goes with rooms and room_history.
Here is my query for joining all three tables.
"SELECT users.*,rooms.room_id,rooms.room_name,rooms.type,room_history.start_date,room_history.end_date FROM users " +
"LEFT JOIN room_history ON room_history.user_id= users.user_id " +
"LEFT JOIN rooms ON room_history.room_id = rooms.room_id";
Using above query following error occurs.
syntax error (missing operator) in query expression 'room_history.user_id = users.user_id LEFT JOIN rooms on room_history.room_id = rooms.room_i'
I check/change my database tables name, compact the database.
Is it possible to get to fundamentals here - and design this query using the Access query design view tool? ... rather than attempting to resolve this using a text based sql statement...
Once you make the query in Access using the query design feature, and verify that it runs correctly in returning the correct record set - - then use the option to put it into SQL View (rather than Design View) in order to see the text based sql statement.
Try with table alias's instead - the problem appears to be Type is a reserved SQL keyword:
SELECT U.*,R.room_id,R.room_name,R.[type],RH.start_date,RH.end_date FROM users U
LEFT JOIN room_history RH ON RH.user_id= U.user_id
LEFT JOIN room R ON RH.room_id = R.room_id
Your problem is your naming convention.
You used
rooms.type
where type is a reserved word of your database.
the error you receive
syntax error (missing operator) in query expression 'room_history.user_id = users.user_id LEFT JOIN rooms on room_history.room_id = rooms.room_i'
pertains to naming conventions which below link discusses.
https://support.microsoft.com/en-ph/help/932994/you-receive-an-error-message-when-you-run-a-query-in-microsoft-access
If you would insist to use your query "as is" you may simply put brackets ([]) on all of your table names that are reserve words, (e.g [type], [start_date],[user_id])
I have a table in a database and one of the columns contains xml stored as nvarchar. I need to write a query and get information based on data stored in that column.
So I ended up writing the following native sql query using NHibernate:
string sql = #"SELECT a.id as s
FROM [DBT].[dbo].[tb_myTable] a
where (cast (a.vchExtendedInfo as XML)).value('/*[1]/#type','NVARCHAR(MAX)')='deal'"
ISQLQuery sqlQuery = HibernateUtil.GetCurrentSession().CreateSQLQuery(sql)
And it throws an error: 'ArgumentOutOfRangeException' - Length cannot be less than zero.Parameter name: length.
After a little bit of testing I found out, that NHibernate is trying to parse my query and that '/*[1]/#type' line is probably the cause. (This is actually a simplified example and all other conditions work nicely if I remove this one).
So, how do I escape/fix my query to make it work?
I guess this is because of the "#" in the query.
Did you already try using parameters?
string sql = #"SELECT a.id as s
FROM [DBT].[dbo].[tb_myTable] a
where (cast (a.vchExtendedInfo as XML)).value(:type,'NVARCHAR(MAX)')=:value"
ISQLQuery sqlQuery = HibernateUtil.GetCurrentSession()
.CreateSQLQuery(sql)
.SetAnsiString("type", "/*[1]/#type")
.SetAnsiString("value", "deal");
I am fairly new to C# and SQL, so this may be a very easy question to answer.
I am trying to add a row to a table (EventList) through C# code. I have opened my SqlConnection without any issues, and I know I am connected to the correct database as some earlier code is querying for rows in one of the tables and it's returning the correct keys.
The SQL query to insert the row into the table is like this:
sqlCmd.CommandText =
"insert into EventList values ('" +
eventListIdentifier + "','" +
eventId.ToString() + "')";
sqlCmd.ExecuteNonQuery();
I am using SQL Server Management Studio Express to view the tables in my database. After running the above query, I right-click on the EventList table and click Open Table.
I am not seeing the new row added based on the above call. Any ideas what I may be doing wrong?
Update 1
The data types I'm inserting are:
eventListIdentifier (varchar(100), null)
eventId (varchar(8000), null)
I manually created the same query in SSMS like this:
insert into EventList(eventListIdentifier, eventId ) values('test', 'blah')
and says the following:
(1 row(s) affected)
However no row has been added to the table when I right-click on it and open it.
Update 2
Output of System.Console.WriteLine(sqlCmd.CommandText); as requested by #billinkc:
insert into EventList(eventListIdentifier, eventId) values ('7/09/2011 10:43:55 AM','7')
Any errors? What happens if you output the SQL statement instead of executing it and copy/paste it into SSMS?
Try specifying the columns in the insert:
insert into EventList(col1, col2) values (...)
Also, use parameters instead of string concatenation. The reasons for doing so are well documented in about 200000 questions here already. Just search for SQL injection.
Don't use Open Table due to the cache/refresh bug I pointed out in my comment. Just re-run the same query in a query window:
SELECT * FROM dbo.EventList
-- WHERE EventId = <EventId>
;
You haven't really provided enough detail to help. At the least, it would be helpful to know:
Are there any errors?
Is the code snippet you posted in a try/catch block?
What datatypes are the variables you are inserting?
Are you using a Transaction that wasn't committed?
Finally, how is the table sorted? Are there any indexes, including a primary key?
If you run a SELECT in Management Studio based on the value in eventId, do you see the record?
I have a current requirement to determine the table hierarchy from a sql statement within c#. For example, consider the following sql statement:
Select Table1.*, Table2.* from Table1
left join table2 on Table1.parentCol = Table2.childCol
That might return 7 columns, 3 for Table1 and 4 for table2. I need to know the column names, and ideally (though not mandatory) their types.
I have no control over what SQL Statement will be used, as this is a user entered field. In C# it's a very basic task to open a connection and create an SqlCommand using that statement. I have freedom to run the SQL into a SqlDataReader, or any other System.Data.SqlClient class if necessary, however I cannot find any combination that will return the columns, rather than the actual column values.
Is anyone able to help?
Many thanks and best regards
You cannot do what you are asking (easily).
More to the point, do not let users enter arbitrary TSQL (You will regret it at some point...).
Instead, create a 'Search' form that allows entering various params and use a parameterised query onto a view that joins all the tables/columns required.
There's no direct way. You'll need to parse names of all the tables from the sql query.
Once you have done that you'll need to write few queries on Information_Schema to get raw data for what you are looking for.
If you are on SQL Server, you may want to use Catalog View
ex-
Select * from sys.tables where [Name] = 'MyTable'