SQL2005 INSERT / IDENTITY help required
-
* Please note i have also posted this in SQL forum as i dont know which is most appropriate. If a mod feel it is wrongly placed here i appologise, feel free to delete. Problem: Hi, I need help with an sql query please. I wish to insert a new record into a table, and instantly retreive the new records id. Is it possible to do this in one sql statement rather than an INSERT followed by the SELECT statement? My INSERT looks like this: string conn = System.Configuration.ConfigurationManager.ConnectionStrings["artisanConnectionString"].ConnectionString; SqlConnection uniqueCon = new SqlConnection(conn); //set SQL statement SqlCommand cmd = new SqlCommand("INSERT INTO [tbl_Additional] (add_Item, add_Price) VALUES ('" + TextBox10.Text + "', '" + TextBox11.Text + "') ", uniqueCon); cmd.Connection.Open(); try {//insert/ add new record //commit to database cmd.ExecuteNonQuery(); //clear form add/edit TextBox10.Text = null; TextBox11.Text = null; //confirm to user ShowMessageBox("New unique Item Added!"); //update dataset GridView2.DataBind(); } catch { ShowMessageBox("Unable to add record!!! Please try again later."); } cmd.Connection.Close(); Any help would be greatly appreciated. Thanks & Happy Easter!
-
* Please note i have also posted this in SQL forum as i dont know which is most appropriate. If a mod feel it is wrongly placed here i appologise, feel free to delete. Problem: Hi, I need help with an sql query please. I wish to insert a new record into a table, and instantly retreive the new records id. Is it possible to do this in one sql statement rather than an INSERT followed by the SELECT statement? My INSERT looks like this: string conn = System.Configuration.ConfigurationManager.ConnectionStrings["artisanConnectionString"].ConnectionString; SqlConnection uniqueCon = new SqlConnection(conn); //set SQL statement SqlCommand cmd = new SqlCommand("INSERT INTO [tbl_Additional] (add_Item, add_Price) VALUES ('" + TextBox10.Text + "', '" + TextBox11.Text + "') ", uniqueCon); cmd.Connection.Open(); try {//insert/ add new record //commit to database cmd.ExecuteNonQuery(); //clear form add/edit TextBox10.Text = null; TextBox11.Text = null; //confirm to user ShowMessageBox("New unique Item Added!"); //update dataset GridView2.DataBind(); } catch { ShowMessageBox("Unable to add record!!! Please try again later."); } cmd.Connection.Close(); Any help would be greatly appreciated. Thanks & Happy Easter!
Before you attempt resolving this problem on hand, seriously consider a re-design of your database query approach. Your application is vulnerable for SQL Injection attacks.
Vasudevan Deepak Kumar Personal Homepage
Tech Gossips
A pessimist sees only the dark side of the clouds, and mopes; a philosopher sees both sides, and shrugs; an optimist doesn't see the clouds at all - he's walking on them. --Leonard Louis Levinson