A friend of mine has a problem, she has done a project in c# and everything looks fine, but the problem is that, she gets error with the SQL query when she puts it in the code, but when we try the code in microsoft SQL Server it works.
Here is thee example f the code where the error shows:
DataSet dsDelP = new DataSet();
string sql = "";
sql = "SELECT Grupi_ID, (p.emri + ' ' + p.mbiemri) as Profesori , k.EmriKlases as Klasa, d.emri as Dita, Ora_fillimit as Fillimi, Ora_mbarimit as Mbarimi";
sql += "FROM grupetOraret gro";
sql += "inner join Profesori p on gro.Profesori_ID=p.Profesor_ID";
sql += "inner join Klasa k on gro.Klasa_ID=k.Klasa_ID";
sql += "inner join Dita d on gro.ID_Dita=d.ID_dita";
SqlDataAdapter daDelP = new SqlDataAdapter(sql, con);
daDelP.Fill(dsDelP, "grupetOraret");
dataGridViewKerkoOrarin.DataSource = dsDelP.Tables[0].DefaultView;
You have no spaces. You should add them in every line (in its beggining or ending). This is how it should look like, assuming the query itself is correct (as soon as you checked it already):
sql = "SELECT Grupi_ID, (p.emri + ' ' + p.mbiemri) as Profesori , k.EmriKlases as Klasa, d.emri as Dita, Ora_fillimit as Fillimi, Ora_mbarimit as Mbarimi ";
sql += "FROM grupetOraret gro ";
sql += "inner join Profesori p on gro.Profesori_ID=p.Profesor_ID ";
sql += "inner join Klasa k on gro.Klasa_ID=k.Klasa_ID ";
sql += "inner join Dita d on gro.ID_Dita=d.ID_dita ";
Appending to the sql variable doesn't automatically insert newlines, so sql will end up looking like
...FROM grupetOraret groinner join Profesori p on gro.Profesori_ID=p.Profesor_ID...
Note that grupetOraret gro and inner join have no space between them.
Try using # for multi-line string literals, makes things easier and more efficient:
string sql = #"
SELECT Grupi_ID, (p.emri + ' ' + p.mbiemri) as Profesori , k.EmriKlases as Klasa, d.emri as Dita, Ora_fillimit as Fillimi, Ora_mbarimit as Mbarimi
FROM grupetOraret gro
inner join Profesori p on gro.Profesori_ID=p.Profesor_ID
inner join Klasa k on gro.Klasa_ID=k.Klasa_ID
inner join Dita d on gro.ID_Dita=d.ID_dita";
Your SQL looks like this after the strings are concatenated:
SELECT ... as MbarimiFROM .... on gro.Profesori_ID=p.Profesor_IDinner ...
You need a space between the last word on each line and the first word on the next line:
string sql = "... as Mbarimi";
sql += " FROM ...";
sql += " inner join Profesori p on gro.Profesori_ID=p.Profesor_ID";
sql += " inner join Klasa k on gro.Klasa_ID=k.Klasa_ID";
sql += " inner join Dita d on gro.ID_Dita=d.ID_dita";
Related
I have the following table structure of my database:
db structure
My aim is to output every row of tbl_Therapeuten (these are my employees) with the name of their trainings (in german "Fortbildung").
The names of the trainings are stored in tbl_Forbildungen. And the trainings which each employee has is stores in tbl_Therapeut_Fortbildung. For the output I want to show the name of the training, not the id.
Like this:
output
I am programming in C#, SQL Server.
First I tried this:
string sSQL = "SELECT t.*, STRING_AGG(tf.Id_Fortbildung, ';') AS Fortbildungen " +
"FROM tbl_Therapeuten t " +
"FULL OUTER JOIN tbl_Therapeut_Fortbildung tf on t.Id = tf.Id_Therapeut ";
But this brings an error containing that I don't use tbl_Therapeuten.Id in an aggregate function or in a Group by clause.
Next I tried this:
string sSQL = "SELECT t.Id, t.Nachname, STRING_AGG(tf.Id_Fortbildung, ';') AS Fortbildungen " +
"FROM tbl_Therapeuten t " +
"FULL OUTER JOIN tbl_Therapeut_Fortbildung tf on t.Id = tf.Id_Therapeut " +
"GROUP BY t.Id, t.Nachname";
This worked (except displaying the name of the training but the Id) but I don't want to explicitly name every column of tbl_Therapeuten. I want to use "t.*". But this is not working:
string sSQL = "SELECT t.*, STRING_AGG(tf.Id_Fortbildung, ';') AS Fortbildungen " +
"FROM tbl_Therapeuten t " +
"FULL OUTER JOIN tbl_Therapeut_Fortbildung tf on t.Id = tf.Id_Therapeut " +
"GROUP BY t.*";
So I need some help :)
And what I also don't know how to do is to display the name of the trainings instead of the id.
Thanks for your help!
You might find that a correlated subquery provides better performance (by avoiding the outer aggregation) and allows you to avoid listing all columns from t:
SELECT T.*,
(SELECT STRING_AGG(F.Name, ';')
FROM tbl_Therapeut_FortBildung TF JOIN
tbl_FortBildungen F
ON F.Id = TF.Id_FortBildung
WHERE TF.Id_Therapeut = T.Id
) as Fortbildungen
FROM Therapeuten T
I think this is what you need.
SELECT T.Id,T.Name,T.Street,T.BirthDate,STRING_AGG(F.Name,';')
FROM Therapeuten T
LEFT JOIN tbl_Therapeut_FortBildung TF ON TF.Id_Therapeut=T.Id
LEFT JOIN tbl_FortBildungen F ON F.Id=TF.Id_FortBildung
GROUP BY T.Id,T.Name,T.Street,T.BirthDate
As far as I know SQL server does not support the GROUP BY *, so you will have to specify the column names.
Hello! I tried to connect 4 tables form Access in Visual Basic c# and I got "Syntax error (missing operator) in query expression", can you please help me? Thanks!
string query = "Select e.Denumire_Ech, e.Descriere_Ech, e.UnitateMasura, e.Pret_Vanzare, o.Cantitate_EchOf From ECHIPAMENTE e INNER JOIN OFERTE o ON e.Cod_Echipament = o.Cod_Echipament INNER JOIN CONTRACTE c ON c.Cod_Oferta = o.Cod_Oferta INNER JOIN FACTURI f ON f.Nr_Contract = c.Nr_Contract WHERE Nr_Contract='" + CB_Contract.Text + "'";
You have multiple tables you are joining across but have not specified which table your WHERE clause is looking up on.
string query = "Select e.Denumire_Ech, e.Descriere_Ech, e.UnitateMasura, e.Pret_Vanzare, o.Cantitate_EchOf From ECHIPAMENTE e INNER JOIN OFERTE o ON e.Cod_Echipament = o.Cod_Echipament INNER JOIN CONTRACTE c ON c.Cod_Oferta = o.Cod_Oferta INNER JOIN FACTURI f ON f.Nr_Contract = c.Nr_Contract WHERE c.Nr_Contract='" + CB_Contract.Text + "'";
Also you should watch out for SQL injection and unusual characters in the CB_Contract.Text For example if there is a ' character then the sql will fail.
Anyone know why got syntax error? I think there are no reserve words inside right?
C# Command
cmd.CommandText = "SELECT ordertable._name, ordertable.quantity, food_menu.food_price, beverage_menu.beverage_price" +
"FROM ordertable" +
"INNER JOIN food_menu ON ordertable._name = food.foodname" +
"INNER JOIN beverage_menu ON beverage_menu.beverage_name' = ordertable._name" +
"WHERE ordertable.tablenum = '1'";
Error:
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 'JOIN food_menu ON ordertable._name = food.foodnameINNER JOIN
beverage_menu ON be' at line 1
You are missing spaces. At the moment your query will be like FROM ordertableINNER JOIN food_menu .... You could use the multiline syntax to make it simpler
cmd.CommandText = #"SELECT ordertable._name, ordertable.quantity, food_menu.food_price, beverage_menu.beverage_price
FROM ordertable
INNER JOIN food_menu ON ordertable._name = food_menu.foodname
INNER JOIN beverage_menu ON beverage_menu.beverage_name = ordertable._name
WHERE ordertable.tablenum = 1";
Remove unnecessary concatenation from string, you are getting an error because your query needs some spaces which you have not specified before join.
cmd.CommandText = "SELECT ordertable._name,
ordertable.quantity,
food_menu.food_price,
beverage_menu.beverage_price
FROM ordertable
INNER JOIN food_menu
ON ordertable._name = food.foodname
INNER JOIN beverage_menu
ON beverage_menu.beverage_name = ordertable._name
WHERE ordertable.tablenum = 1";
So I'm retrieving data from the database using odbc. One of my fields, which was causing the problem, is AutoNumber. In my query when I use, '" convert.toint64(empid)"', I get an error of data type missmatch. But when I used parameter, it worked perfectly. Can someone tell me what is the difference. As far as I know, AutoNumber is a long integer and long int is 64, right?
here are both of my queries:
string cmdText = "SELECT p.projID, p.projName, a.wageperday " +
"FROM ((projects p INNER JOIN assigns a ON p.projID = a.projname) " +
"INNER JOIN empos e ON a.employeeID= e.ID) " +
"WHERE a.employeeID = ?";
OdbcCommand assignslist = new OdbcCommand(cmdText, _connection);
assignslist.Parameters.AddWithValue("#empID", empid);
OdbcDataReader readassigns = assignslist.ExecuteReader();
GridView1.DataSource = readassigns;
GridView1.DataBind();
(this one works fine)
string cmdText = "SELECT p.projID, p.projName, a.wageperday " +
"FROM ((projects p INNER JOIN assigns a ON p.projID = a.projname) " +
"INNER JOIN empos e ON a.employeeID= e.ID) " +
"WHERE a.employeeID = '" + convert.toint64( empid ) + "';
OdbcCommand assignslist = new OdbcCommand(cmdText, _connection);
OdbcDataReader readassigns = assignslist.ExecuteReader();
GridView1.DataSource = readassigns;
GridView1.DataBind();
for this one, i get an error even if I removed the conversion, I get an error.
One more question, I don't understand INNER JOIN perfectly and the above code was from a user here who helped me. I don't understand why did he use "FROM ((projects p INNER JOIN assigns a ON p.projID = a.projname) " +
"INNER JOIN empos e ON a.employeeID= e.ID)"
two brackets -- I mean a bracket inside a bracket. And if I wanna join a 4th or 5th table do I have to put it inside a bracket aside from the main bracket? An example would be much appreciated!
If a.employeeID is a number then your problem are the quotes and the concatenation of a number to a string.
"WHERE a.employeeID = " + convert.toint64(empid).ToString()
but this make no sense because you have a string to build so, you could simply write
"WHERE a.employeeID = " + empid.ToString();
however use always the parameterized query. That is the correct way to go.
A parameterized query allows the Framework code to pass the parameters with the correct format and you don't have to worry about quoting values, format of dates and decimal separators. (And last but not least, you avoid any possibilities of Sql Injection)
For the second part of your question, JOIN is used to put togheter data from two tables, when you have more than one JOIN the parenthesys help to understand how the grouping from the tables are perfomed. First the data from projects and assigns are grouped together following the rules of the INNER JOIN then the resulting set of data is joined with the data from the employee table following the rules of the second join.
In your second query, instead of using convert.toint64( empid ) try using empid.ToString():
"WHERE a.employeeID = " + empid.ToString();
The error you were receiving was due to the fact that you were trying to concatenate a string with an integer.
With regards to the INNER JOINs you are using, the use of the brackets is dependant upon the database you are using. In most cases, you will not need the brackets at all and they can be removed without any issue, so you could rewrite the query to:
string cmdText = "SELECT p.projID, p.projName, a.wageperday " +
"FROM projects p " +
"INNER JOIN assigns a ON p.projID = a.projname " +
"INNER JOIN empos e ON a.employeeID = e.ID " +
"WHERE a.employeeID = " empid.ToString();
You're trying to add a string and an integer, which isn't allowed automatically. You'd have to convert the number to a string first, like this:
"WHERE a.employeeID = '" + empid.ToString() + "';
But, using parameters is the better way for other reasons (best habit to be in, to avoid SQL-injection attacks, etc.).
conn.Open();
String sql = "select CATEGORIES.CAT_NAME,PRODUCTS.PRO_MODEL,PRODUCTS.PRO_NAME,PRODUCTS.PRO_PRICE,PRODUCTS.PRO_IMAGE,PRODUCTS.PRO_DESCRIPTION,PRODUCTS.PRO_STATUS,PRODUCTS.PRO_ACTIVE" +
"from PRODUCTS INNER JOIN CATEGORIES on PRODUCTS.CAT_ID = CATEGORIES.CAT_ID";
My Query SQL runs fine in MYSQL Server but it has error in C# code Incorrect syntax near the keyword 'INNER'. hope have answer soon
You need to add space between (.PRO_ACTIVE" and "from) string concatenation.
.PRO_ACTIVE " + "from...
So your query should be:
String sql = "select CATEGORIES.CAT_NAME,PRODUCTS.PRO_MODEL,PRODUCTS.PRO_NAME,PRODUCTS.PRO_PRICE,PRODUCTS.PRO_IMAGE,PRODUCTS.PRO_DESCRIPTION,PRODUCTS.PRO_STATUS,PRODUCTS.PRO_ACTIVE"
+ " " +//explicit space
"from PRODUCTS INNER JOIN CATEGORIES on PRODUCTS.CAT_ID = CATEGORIES.CAT_ID";
You need a space at the end of the first line of your string -- C# doesn't put line feeds in.
change it to:
String sql = "select CATEGORIES.CAT_NAME,PRODUCTS.PRO_MODEL,PRODUCTS.PRO_NAME,PRODUCTS.PRO_PRICE,PRODUCTS.PRO_IMAGE,PRODUCTS.PRO_DESCRIPTION,PRODUCTS.PRO_STATUS,PRODUCTS.PRO_ACTIVE" +
" from PRODUCTS INNER JOIN CATEGORIES on PRODUCTS.CAT_ID = CATEGORIES.CAT_ID";
A space was missing between "..PRODUCTS.PRO_ACTIVE" and "from PRODUCTS.."