insert code error - c#

insert into customer (Advance,status)
values(#Advance,#status)
where Name='" + txtcname.Text.Trim() + "'";
in the above insert statement in going to insert 2 values based in condition but i'm getting error in where condition...
incorrect syntax near keyword where
this is the error

Insert query do not needs Where clause. Just write
insert into customer (Advance, status) values(#Advance, #status)
Are you trying to insert or update? if you need to update an existing record then use update instead of insert like this:
update customer set Advance=#Advance, status=#status
where Name='" + txtcname.Text.Trim() + "'";
EDIT
Aforementioned update query will serve the purpose but its recommended to use stored procedures/parameterized queries for SQL injection safety. You should following use approach:
Private void UpdateRecord(string advance,string status, string name)
{
//SqlConnection con
SqlCommand cmdUpdate = new SqlCommand("update customer set Advance = #Advance, status = #Status where Name=#Name", con);
cmdUpdate.Parameters.AddWithValue("#Advance", advance);
cmdUpdate.Parameters.AddWithValue("#Status", status);
cmdUpdate.Parameters.AddWithValue("#name", name);
cmdUpdate.ExecuteNonQuery();
}
Pass your data as following:
UpdateRecord(#Advance,#Status,txtcname.Text.Trim());

You can't use 'where' in an insert-statement.
To achieve the same result, you can insert all entries and delete the wrong.
You can use a select-statement after an insert, where you select entries from a table into another. This could be a solution for you, too.
Insert into customer (advance, status) values (...)
select advance, status
from anotherCustomerTable
where ...
P.S. try to prepare the where-part, too.

You can not add where clause with values. You can achieve this with following way
if you really want to insert new rows else you can follow the #Munawar solution
insert into customer (Advance, status)
SELECT #Advance,#status
FROM customer where Name='" + txtcname.Text.Trim() + "'"

Related

How to use LAST_INSERT_ID() in c# windows form?

In database I have three tables-
patient(patientID,fName,lName)
illness(diseaseID,diseaseName)
patientDisease(patientID, diseaseID, dateChecked)
patientID and diseaseID are index.
So on in c# I have three textboxes fNameTxt and lNameTXT, diseaseTxt.I want to store the name in patient table and disease name in illness table. Besides, I have to record patientID and diseaseID in patientDisease table as well. For patient table, I used following code. I knew, I can use
SET #variable = LAST_INSERT_ID()
to get the id, but realised c#(visual studio) doesnt recognize it. Basically, I couldnt make the overall statement. Could anybody help me to get through this condition please.
string connStr = #"server=localhost; DATABASE=mario;User ID=root;Password=;";
MySqlConnection conn1 = new MySqlConnection();
conn1.ConnectionString = connStr;
MySqlCommand cmd = conn1.CreateCommand();
cmd.CommandText = "INSERT INTO patient(patientID,fName, lName)"
+ "Values("NULL",'" + fNameTxt.Text + "','" + lNameTxt.Text + "');";
conn1.Open();
cmd.ExecuteNonQuery();
I searched some other questions here, but they are almost about suggesting the use of LAST_INSERT_ID() but not how to use it.
It will be much better if you use stored procedures
INSERT INTO patient (patientID,patientID,lName)
VALUES("NULL",'" + fNameTxt.Text + "','" + lNameTxt.Text + "');
SET #last_id_in_patient = LAST_INSERT_ID();
INSERT INTO patientDisease (patientID,diseaseID,dateChecked)
VALUES( #last_id_in_patient ,NULL,'text'); # use ID in second table";
Now You can update your PatientDisease table for particular PatientId.
You can use this to get the last inserted id:
"SELECT * FROMtable(column) WHERE id = last_insert_id();
And use this if you want to insert a last id:
"INSERT INTO table(column) VALUES (LAST_INSERT_ID())";
Hope this might be useful.

SQL INSERT INTO statement with WHERE Statement

Can you use a WHERE statement within an INSERT INTO statement in SQL?
here is what i am currently trying to do.
INSERT INTO AssetComponents(ComponentID, ComponentDescription)
VALUES (#ComponentType, #CompDescr)
WHERE (AssetTagNumber = #TagNo)
But the compiler is having an issue with the WHERE statement.
thanks
***UPDATE****
This is the full code that i am using so far with amendments
protected void AddBut_Click(object sender, EventArgs e)
{
//still passing the Asset tag number forward here
var ID = Request.QueryString["Id"];
string sql = "";
using (SqlConnection con = new SqlConnection("Data Source: *******************)
{
sql = "IF (AssetTagNumber = #TagNo) " +
"BEGIN " +
"INSERT INTO AssetComponents(ComponentID, ComponentDescription) " +
"VALUES (#ComponentType, #CompDescr) " +
"END ";
using (SqlCommand cmd = new SqlCommand(sql, con))
{
// try
// {
cmd.Parameters.AddWithValue("#TagNo", ID);
cmd.Parameters.AddWithValue("#ComponentType", TypeDDL.Text.Trim());
cmd.Parameters.AddWithValue("#CompDescr", DescrTB.Text.Trim());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("ComponentDetails.aspx");
// }
// catch (SqlException ex) { MessageBox.Show(" "); }
// catch (Exception ex) { MessageBox.Show(" "); }
}
}
}
Im sorry i was not clear enough first time around.
What i want to do is insert a new record with a clause that says if this record has an existing PK then use this key to insert another entry for that record
Apologies once again
Why don't you just use IF-clause?
IF (AssetTagNumber = #TagNo)
BEGIN
INSERT INTO AssetComponents(ComponentID, ComponentDescription)
VALUES (#ComponentType, #CompDescr)
END
For statements with WHERE script should look similar to:
INSERT INTO AssetComponents(ComponentID, ComponentDescription)
SELECT #ComponentType, #CompDescr
FROM <table>
WHERE (AssetTagNumber = #TagNo)
You can not "conditionally insert" like that. The WHERE clause is only available for SELECT, UPDATE or DELETE.
To check whether you need to INSERT a new record, you need to use IF, as in:
IF NOT EXISTS (SELECT ...)
INSERT INTO ...
if EXISTS (select * from AssetComponents where AssetTagNumber = #TagNo)
Begin
INSERT INTO AssetComponents(ComponentID, ComponentDescription)
(#ComponentType, #CompDescr)
End
Use this:
UPDATE AssetComponents
Set ComponentID=#ComponentType, ComponentDescription=#CompDesc
Where AssetTagNumber = #TagNo
WHERE clause is something that helps to filter record, so it preferably uses with either SELECT or UPDATE. For INSERT we normally use IF NOT EXISTS clause.
See Examples:
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/724ab6f3-413f-4c59-9b68-776f3ecfa899/insert-if-not-exists-into
http://msdn.microsoft.com/en-us/library/ms174335.aspx
Also, after looking at documentation, we can see that INSERT statement has NO support for WHERE clause.
If records already exists you can perform eith UPDATE or DELETE with INSERT operations.
You can try like:
IF NOT EXISTS (SELECT * FROM AssetComponents WHERE (AssetTagNumber = #TagNo))
INSERT INTO AssetComponents(ComponentID, ComponentDescription) VALUES (#ComponentType, #CompDescr)
ELSE
--UPDATE fields
Consider INSERT SELECT:
INSERT INTO AssetComponents(ComponentID, ComponentDescription)
SELECT [fill out here] AS ComponentID,
[fill out here] AS ComponentDescription
FROM somesource
WHERE [condition]
This is a specialty of MS SQL Server so will not work in other databases. It sort of requires that your data are already in another table or other source that you can query.

I have inserted a row, I want to get it's ID and plus it with an int and insert in that row

I have inserted a row into my table, and I want to get it's ID and plus it with an int and inserted in that row.
But I don't know how to get it's ID.
Here is the insert code:
objCommand.Connection = objConnection;
objCommand.CommandText = "INSERT INTO Moin " +
" (Title, TotalID, Code ) " +
"VALUES (#Title , #TotalID, #Code )";
objCommand.Connection = objConnection;
objCommand.CommandText = "INSERT INTO Moin " +
" (Title, TotalID, Code ) " +
"VALUES (#Title , #TotalID, #Code ) SELECT SCOPE_IDENTITY()";
object id = objCommand.ExecuteScalar();
Try using the OUTPUT clause of SQL Server in your query - it can return any of the just inserted value (here I'm assuming your column is called ID - adapt as needed):
objCommand.Connection = objConnection;
objCommand.CommandText = "INSERT INTO Moin(Title, TotalID, Code ) " +
"OUTPUT Inserted.ID " +
"VALUES (#Title , #TotalID, #Code ); "
and then execute it like this:
int result = (int)objCommand.ExecuteScalar();
Since you're returning just one row and one column (just the INT), you can use .ExecuteScalar() to retrieve that value back from the INSERT statement.
With the OUTPUT clause, you can return any values just inserted - not just the identity column. So you could also return values that are filled by the database with default values, or whatever you need. If you return multiple values, you need to use a data reader to read them all - ExecuteScalar() only works for a single value.
But, as Anders correctly mentioned - using an ORM like Entity Framework would do all of this automatically for you and you wouldn't have to deal with those raw SQL commands anymore....
Building SQL commands in strings should be considered a legacy technique. If you use Entity Framework or linq-to-sql the retrieval of the id is handled automatically for you.
With pure SQL, use the SCOPE_IDENTITY() function to retrieve the id of the inserted element.

SQL syntax near WHERE?

I'm a newb here, and it may be because I've been up since yesterday morning, but I can't find my error here in this insert statement. My handler asked me not to parameterize for this training project (it won't be deployed), so no worries for the injection vulnerabilities. Anyway, the query's right, the data types are correct, and the table and field names are spelled correctly. What am I missing here? And is there a better way to find it than just staring at the screen until it comes to you?
protected void BtnSubmit_Click(object sender, EventArgs e)
{
string x = Request.QueryString["SubId"];
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string comQuery = "INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES ('" + "decline" + "', '" + TbComments.Text + "', 2) WHERE SubmissionId =" + x;
using (SqlConnection sqlConn = new SqlConnection(connectionString))
{
sqlConn.Open();
using (SqlCommand comCmd = new SqlCommand(comQuery, sqlConn))
{
comCmd.ExecuteNonQuery();
}
}
}
An INSERT can't have a WHERE clause. It makes no sense to have one, you're putting data in, not narrowing it down.
If you're trying to change preexisting data, that's an UPDATE, not an INSERT. Here's an example:
"UPDATE Submission
SET Status='decline', StatusComment='" + TbComments.Text + "', StatusValue = 2
WHERE SubmissionId = " + x
That is incorrect INSERT syntax. Correct INSERT syntax is:
INSERT INTO tableName (columnList) VALUES (valueList)
columnList and valueList must have same count of items and values must be of type expected by columns.
or
INSERT INTO tableName (columnList)
SELECT columnList2
FROM tableName2
WHERE conditionsFromTable2
columnList and columnList2 must have same count of items of same types. You can use any complicated select joined over multiple tables with condition applied on data from these tables.
You need to use UPDATE, not INSERT
INSERT insert new row, therefore WHERE makes no sense
Where clause is not allowed in Insert query. Form your code I guess that you need to use Update query.
You'r trying to INSERT INTO Submission data from TbComments. So you need to SELECT the data from TbComments and then INSERT INTO Submission
string comQuery =
"INSERT INTO Submission (
Status,
StatusComment,
StatusValue)
SELECT
'decline',
TbComments.Text,
2)
FROM TbComments
WHERE SubmissionId =" + x;
So your SQL statement is:
"INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES (blah) WHERE SubmissionId =" + x;
The problem is definitely the WHERE. WHERE isn't valid for INSERT - See the MSDN documentation for the Insert command. Since you're filtering by SubmissionId, you probably want to do an UPDATE instead.
As for a better way of finding the problem, learning to use the MSDN documentation is a good step. A quick Google search for "msdn t-sql insert" will give you the page I linked to earlier in this answer. Documentation, experience, Google and Stack Overflow. That's how you find solutions :)

SELECT inside INSERT query?

I am trying to insert the user id from table users inside table session , field session_user, using textbox , but it seems it doesn't work ..
Here is my SQL code, I am using visual studio and trying to insert to a SQL Server table
SqlCommand addsession = new SqlCommand
("insert into dbo.session(session_user)
values (select user_id from dbo.users where username = '" + TextBox1.Text + "')",
badersql);
You shouldn't use the VALUES keyword when you're doing an INSERT ... SELECT:
insert into dbo.session (session_user) select user_id from dbo.users ...
If you are inserting the result of a query into another table, just leave out the VALUES keyword.
The VALUES keyword can always be replaced by a simple SELECT 'dummy', 'value' of the values you want to insert, but I suggest you still use VALUES whenever you want to make it clear that your results do not come from a query.
That being said, please use parameterized queries!! Imagine if someone were to enter the following text into TextBox1:
' or 1 = 1
What would happen?
To insert records from a query use this insert syntax:
insert into dbo.session (session_user)
select user_id from dbo.users where username = '" + TextBox1.Text + "'
You may want to do a select top 1 userid if you are expecting one row to be inserted like in the values statement.
i did it , the problem was that i can not name my record session_user , so i replaced with se_user and that solve the problem .
thank u all for ur help
so the correct sql statement is
insert into sessions (se_user) select USER_ID from users where username = '';

Categories