A column named "MYTEST" is generated automatically in my sql server database - c#

I have a winforms project in which I add a table from sql server database into a Datagridview.
I don't know why a column named "MYTEST" is generated automatically in my sql server DB when I make changes like updating the table in the database/updating the datagridview.
I have to say that there are lots of sql queries in my project but none of them include "INSERT".
EDIT
Here are the queries:
sql1 = "select CONVERT(Bit,SwActive) AS SwActive, Kod AS Kod ,Nm AS Nm,(CONVERT(char,FromDate,103)) AS FromDate, (CONVERT(char,ToDate,103)) AS ToDate " +
"FROM Mivza " +
"ORDER BY SwActive DESC";
sqlupdate= "update Mivza set SwActive='" + SwActive + "',MivzaButal='" + MivzaButal + "' " +
"where Kod='" + Kod + "'";
sqlsearch = "select max(isnull(SwActive,0)) as SwActive, max(Mivza.Kod) as Kod, max(Mivza.Nm) as Nm, isnull(Max(convert(char,FromDate,103)), '') as FromDate, isnull(max(convert(char,ToDate,103)),'') as ToDate, Mivza.C as C, max(DateDiff(m,0,FromDate)) as DDF, max(DateDiff(m,0,ToDate)) as DDT " +
"from Mivza " +
"left join Mivza_Prt_All on Mivza_Prt_All.Mivza = Mivza.C " +
"left join Prt on Prt.C = Mivza_Prt_All.Prt " +
"where DateBitul is null and isnull(Mivza.Nm,'') like '%h%' or isnull(Prt.Nm,'') like '%h%' " +
"group by Mivza.C " +
"ORDER BY SwActive DESC, Kod ASC";

Related

Object or column name is missing or empty

I have this problem in C#, I have already run this query in SQL Server and works
SQL query
SELECT Mineria.dbo.Usuario.ID_Usuario, Mineria.dbo.Usuario.Sexo, Mineria.dbo.Usuario.Idioma, Mineria.dbo.Usuario.Edad, Mineria2.dbo.ARTISTA.Nombre_artistic
INTO Mineria.dbo.Objeto
FROM Mineria.dbo.Usuario
INNER JOIN Mineria2.dbo.ARTISTA ON Mineria2.dbo.ARTISTA.Id_Artista=Mineria.dbo.Usuario.ID_Usuario
AND Mineria.dbo.Usuario.ID_Usuario BETWEEN 35 AND 70
ORDER BY ID_Usuario ASC
I can't find the problem on the c# code
SqlCommand comando = new SqlCommand(string.Format("
Select '" + maskedTextBox1.Text + "' , '" + maskedTextBox2.Text + "'
INTO Mineria.dbo.Objeto FROM Mineria.dbo.Usuario INNER JOIN Mineria2.dbo.ARTISTA ON Mineria2.dbo.ARTISTA.Id_Artista=Mineria.dbo.Usuario.ID_Usuario
AND Mineria.dbo.Usuario.ID_Usuario BETWEEN '" + textBox1.Text + "' AND '" + textBox2.Text + "' ORDER BY ID_Usuario ASC"), cn);
It's probably because you're putting single-quotes around the field names (should be nothing since you're using fully-qualified names), and around the integers in the BETWEEN statement (should be nothing because they're numbers, not text):
SqlCommand comando = new SqlCommand(string.Format("
Select " + maskedTextBox1.Text + " , " + maskedTextBox2.Text + "
INTO Mineria.dbo.Objeto FROM Mineria.dbo.Usuario INNER JOIN Mineria2.dbo.ARTISTA ON Mineria2.dbo.ARTISTA.Id_Artista=Mineria.dbo.Usuario.ID_Usuario
AND Mineria.dbo.Usuario.ID_Usuario BETWEEN " + textBox1.Text + " AND " + textBox2.Text + " ORDER BY ID_Usuario ASC"), cn);

MySqlDataAdapter Update table that uses Inner Join

I'm tring to add the Insert, Update and Delete commands to a MySqlDataAdapter which has the data added to it with the command:
//iec211.4521studenti
string lv_sObsTable = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
string lv_sStudTable = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti'";
string lv_sObservatiiCommand = "SELECT o.idObservatie, o.idStudent, s.nume, o.observatie, o.lastUpdate FROM " + lv_sObsTable + " o INNER JOIN " + lv_sStudTable + " s USING (idStudent) ORDER BY s.nume ASC";
mv_dtAdapterObservatii = new MySqlDataAdapter(lv_sObservatiiCommand, mv_sqlConnection);
mv_dtAdapterObservatii.Fill(mv_dsTables, lv_sCurrentTable);
I've serched for an answer and I've found two possible solutions for UPDATE, but both of them give me an error:
string lv_sObsTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
string lv_sStudTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti`";
//VERSION 1
string lv_sCommand = "UPDATE o SET s.idStudent=#idStudent, o.observatie=#observatie FROM " + lv_sObsTB + " AS o INNER JOIN " + lv_sStudTB + " s ON o.idStudent=s.idStudent ";
MySqlCommand lv_sqlCommand = new MySqlCommand(lv_sCommand);
lv_sqlCommand.Parameters.Add("#idStudent", MySqlDbType.Int16, 10, "idStudent");
lv_sqlCommand.Parameters.Add("#observatie", MySqlDbType.VarChar, 255, "observatie");
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommand;
//VERSION 2
string lv_sCommand = "UPDATE " + lv_sObsTB + " SET " + "idStudent=#" + lv_sStudTB + ".idStudent, observatie=#observatie WHERE idObservatie=#idObservatie AND " + lv_sObsTB + ".idStudent IN (SELECT " + lv_sStudTB + ".idStudent FROM " + lv_sStudTB + ")";
MySqlCommand lv_sqlCommand = new MySqlCommand(lv_sCommand);
lv_sqlCommand.Parameters.Add("#" + lv_sStudTB + ".idStudent", MySqlDbType.Int16, 10, "idStudent");
lv_sqlCommand.Parameters.Add("#observatie", MySqlDbType.VarChar, 255, "observatie");
lv_sqlCommand.Parameters.Add("#idObservatie", MySqlDbType.Int16, 10, "idObservatie");
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommand;
The error message for the first version is : "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 'FROM iec211.4521observatii ASS o INNER JOIN iec211.4521studenti s ON o.id' at line 1"
The error message for the second version is: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 '.4521studenti'.idStudenti, observatie='test' WHERE idObservatie=1 ANDiec211.' at line 1"
I don't know how to use the MySQL commands in combination with MySqlCommand and MySqlDataAdapter.
Until now I've used the following command to obtain data for my table:
string lv_sObservatiiCommand = "SELECT * FROM `" + mv_sDatabase + "`.`" + mv_sGroup + "observatii` ORDER BY idStudent ASC";
mv_dtAdapterObservatii = new MySqlDataAdapter(lv_sObservatiiCommand, mv_sqlConnection);
mv_dtAdapterObservatii.Fill(mv_dsTables, lv_sCurrentTable);
In combination with MySqlCommandBuilder to get the update command and the parameters that needed to be setted:
lv_sqlCommandBuilder = new MySqlCommandBuilder(mv_dtAdapterObservatii);
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommandBuilder.GetUpdateCommand();
Can someone please explain to me how to correctly add the insert, update and delete commands to a MySqlDataAdapter that contains an INNER JOIN between 2 tables ?
I know that each table must be in a different data adapter, and they are. The "4521studenti" table is inside "mv_dtAdapterStudenti", which is not included in the code above.
Thank you for the help and I hope this won't be considered as a bad post. :)
Okey. I think I've figured it out.
This is the SELECT command for 4521observatii:
string lv_sStudent = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti`";
string lv_sObservatii = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
string lv_sObservatiiCommand = "SELECT o.idObservatie, o.idStudent, s.nume, o.observatie, o.lastUpdate FROM " + lv_sObservatii + " o INNER JOIN " + lv_sStudent + " s USING (idStudent) ORDER BY s.nume ASC";
// Read data from the server for the current table and add it to the DataSet
mv_dtAdapterObservatii = new MySqlDataAdapter(lv_sObservatiiCommand, mv_sqlConnection);
mv_dtAdapterObservatii.Fill(mv_dsTables, lv_sCurrentTable);
And this is the code for the UPDATE command, inside a different method:
// `iec211`.`4521observatii`
string lv_sObsTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
// `iec211`.`4521studenti`
string lv_sStudTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti`";
string lv_sSelectStudenti = "(SELECT idStudent FROM " + lv_sStudTB + " WHERE idStudent=#idStudent)";
string lv_sCommand = "UPDATE " + lv_sObsTB + " SET idStudent="+ lv_sSelectStudenti + ", observatie=#observatie WHERE idObservatie=#idObservatie";
MySqlCommand lv_sqlCommand = new MySqlCommand(lv_sCommand);
lv_sqlCommand.Parameters.Add("#idStudent", MySqlDbType.Int16, 10, "idStudent");
lv_sqlCommand.Parameters.Add("#observatie", MySqlDbType.VarChar, 255, "observatie");
lv_sqlCommand.Parameters.Add("#idObservatie", MySqlDbType.Int16, 10, "idObservatie");
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommand;
mv_dtAdapterObservatii.UpdateCommand.Connection = mv_sqlConnection;
The idea is that when I use INNER JOIN I bring data from two different tables and put them together. When I used the UPDATE command, the program didn't know which table he was using and gived those errors.
So I thought what if I update the values of 4521observatii and for the column that is used as FOREIGN KEY I assign the value from 4521studenti.
I know it's like "Tell me your name so I can tell you your name.", but it worked for me.
I hope this will help others and you have a better and cleaner solution, pleas tell me :)

SQL C# WPF Query Expanded

I had a query answered here SQL Select All Without Values in Another Table.
I've just been asked to integrate the data from another database. This is what I have at the moment.
string _loanSubcontractor = TableNames.Default.LoansSubcontractors;
string _loanPacific = TableNames.Default.LoansPacific;
string _tools = TableNames.Default.Tools;
string _selectStatement = " SELECT [Tools].[Type], [Tools].[Brand], [Tools].[Serial], [Tools].[Year], [Tools].[Code] ";
string _groupBy = " GROUP BY [Tools].[Type], [Tools].[Brand], [Tools].[Serial], [Tools].[Year], [Tools].[Code], [Tools].[Working] ";
string _searchItems = " ([Tools].Code LIKE #toolSerial OR [Tools].Serial LIKE #toolSerial) AND ([Tools].[Working] = 'True' OR [Tools].[Working] IS NULL) ";
SqlConnection myConnection = new SqlConnection(Connection.Default.ConnectionString);
//Checks the main tool information
myConnection.Open();
SqlCommand getTool = new SqlCommand(
_selectStatement + "FROM [" + _tools + "] LEFT OUTER JOIN [" + _loanSubcontractor + "] ON " +
_tools + ".code = [" + _loanSubcontractor + "].ToolCode FULL JOIN [" + _loanPacific + "] ON " + _tools + ".Code = " +
_loanPacific + ".ToolCode WHERE [" + _loanSubcontractor + "].ToolCode IS NULL AND [" + _loanPacific + "].ToolCode IS NULL AND (" + _searchItems + ")" +
"UNION " +
_selectStatement + " FROM [" + _loanSubcontractor + "] INNER JOIN " + _tools + " ON " + _tools + ".Code = [" + _loanSubcontractor + "].ToolCode " +
"INNER JOIN " + _loanPacific + " ON " + _loanPacific + ".ToolCode = " + _tools + ".Code " + _groupBy +
"HAVING (COUNT(" + _loanSubcontractor + ".ReturnDate) = COUNT(*) OR COUNT(" + _loanPacific + ".ReturnDate) = COUNT(*)) " +
" AND " + _searchItems, myConnection);
getTool.Parameters.Add("#toolSerial", SqlDbType.NVarChar).Value = "%" + toolSerial + "%";
What I have is two loan tables (one for employees and one for subcontractors) because the attribute names are different and the data types are also different. Essentially, I need to check that the tool is working, and the tool is not hired out in either of the loan tables (as shown by the return date being null). There may or may not be a loan in either of the tables.
Also, could someone provide me with a link that shows good formatting techniques for SQL within C#?
i sagest you use linq to SQL . this is a part of ADO.NET and you can use long query with 100 % acres and easy way
msdn.microsoft.com for linq to SQL
LINQ to SQL: .NET Language-Integrated Query for Relational Data
Simple LINQ to SQL in C#

Error with SQL syntax (in Windows form , C#)

I'm trying to insert some data into my table and that's how I try to do it
INSERT INTO OrdersDetail
Values (" + OrderId.Text + ", (SELECT IdProduct FROM Products WHERE ProductName = '" + listBox1.Text + "'), '" + TypeOfProductComboBox.Text + "', '" + OrderQuantity.TextAlign + "', '" + TotalCost.Text + "'");
and I'm geting error I think my syntax is wrong, I'm use query in query to get the product id.
The columns are :
OrderId (int)
ProductId(int)
ProductName(Nvarchar)
OrderQuantity(Nvarchar)
TotalCost(NvarChar)
Thanks
You set your inside SELECT under '. Should be:
var query = "INSERT INTO OrdersDetail Values (" + OrderId.Text + ", (SELECT IdProduct FROM Products WHERE ProductName = '"+ listBox1.Text + "'), '" + TypeOfProductComboBox.Text + "', '" + OrderQuantity.TextAlign + "', '" + TotalCost.Text + "')");
If for example TotalCost.Text is a numeric data type in SQL, use
"..." + OrderQuantity.TextAlign + "', " + Convert.ToDouble(TotalCost.Text) + ")";
As p.s.w.g stated: This is open for SQL injection. Replace it with a parameterized version!
I think the problem is with the first Line and your inside Select.
This should work
INSERT INTO OrdersDetail
Values ('" + OrderId.Text + "',(SELECT IdProduct FROM Products WHERE ProductName ='"+ listBox1.Text + "')," + TypeOfProductComboBox.Text + "','" + OrderQuantity.TextAlign + "','" + TotalCost.Text + "'");
The problem is that you are missing the last bracket, the query should finish with "')" instead of "'" . The initial code started with opening bracket and that is why you didn't get compile errors.
But you should not create such sql queries, use Parameters to avoid SQL injection attacks. You code is vulnerable to them.

how to execute SQL with if condition in c#

how to execute SQL with if condition in c#?
This is my query and went i execute this query i get an error saying "Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'."
I m using MS ACCESS as back end
mycon.ConnectionString = ConnString;
mycon.Open();
string mySelectQuery = "IF (EXISTS (SELECT * FROM Employee AS t1 WHERE t1.ssn ='"+textBox4.Text+"' "+
"))begin UPDATE Employee SET "+
"fname ='"+textBox1.Text+"' ,"+
"minit ='"+textBox2.Text+"' ," +
"lname ='" + textBox3.Text+"', " +
"ssn ='" +textBox4.Text+"', " +
"bdate ='" +textBox5.Text+"', " +
"address ='" +textBox6.Text+"', " +
"sex ='" +textBox7.Text+ "', " +
"salary ='" +textBox8.Text+"', " +
"superssn ='" +textBox9.Text+"', " +
"dno ='" +comboBox2.Text+"'" +
" WHERE ssn = '"+textBox4.Text+"' "+
"end "+
"else "+
" begin "+
" INSERT INTO employee values ('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"','"+textBox6.Text+"','"+textBox7.Text+"','"+textBox8.Text+"','"+textBox9.Text+"','"+comboBox2.Text+"')"+
" end";
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, mycon);
int Success= myCommand.ExecuteNonQuery();
MS Access doesn't support the IF statement. Nor else or begin. You'll have to do this in your C# code, such as performing your "SELECT * FROM Employee AS t1 WHERE t1.ssn ='"+textBox4.Text + "'"; query first and then performing the next one if there are results.
Also, you should either use a parameterized queries or escape the values of you text boxes.
Seems like what you want to happen is UPDATE a record if it Exists in database, else INSERT a record.
You can't do this in one query, so prepare a query for a look-up in database if the record exists, then use the output (isExists or not) to UPDATE or INSERT

Categories

Resources