I have two SQL queries:
SqlCommand cmdone = new SqlCommand("update HardwareDetails Set Transstat = @Transstat where AssetNo = @AssetNo", con);
cmdone.Parameters.AddWithValue(@"Transstat", "Raised");
cmdone.Parameters.AddWithValue(@"AssetNo", txtAsset.Text);
cmdone.ExecuteNonQuery();
cmdone.Dispose();
And:
SqlCommand cmd = new SqlCommand("Insert into TransferRequest(FrmName,FrmEmpId,ToName) values (@FrmName,@FrmEmpId,@ToName", con);
cmd.Parameters.AddWithValue(@"FrmName", txtfrm.Text);
cmd.Parameters.AddWithValue(@"FrmEmpId", Global.transferorid);
cmd.Parameters.AddWithValue(@"ToName", txtName.Text);
cmd.ExecuteNonQuery();
cmd.Dispose();
Is there a way to combine them into a single query?
Put a semi-colon between the two SQL statements, and add all the parameters.
using (SqlCommand cmd = new SqlCommand("UPDATE HardwareDetails SET Transstat = @Transstat WHERE AssetNo = AssetNo; INSERT INTO TransferRequest (FrmName, FrmEmpId, ToName) VALUES (@FrmName, @FrmEmpId, @ToName)", con))
{
cmd.Parameters.AddWithValue(@"Transstat", "Raised");
cmd.Parameters.AddWithValue(@"AssetNo", txtAsset.Text);
cmd.Parameters.AddWithValue(@"FrmName", txtfrm.Text);
cmd.Parameters.AddWithValue(@"FrmEmpId", Global.transferorid);
cmd.Parameters.AddWithValue(@"ToName", txtName.Text);
cmd.ExecuteNonQuery();
}
Comments:
Its best practice (because its safer) to create your cmd
within a using
block.
AddWithValue
should not be used , instead create the SqlParameter
using its constructor and specify the type and precision. Eg cmd.Parameters.Add(new SqlParameter("@Transstat", SqlDataType.VarChar, 6) { Value = "Raised"});
As pointed out by Liam as it stands this does break the Single Responsibility Principle . Personally I would only use this method if the two statements are linked/related in some way.
string query = @"
update HardwareDetails Set Transstat = @Transstat where AssetNo = @AssetNo
Insert into TransferRequest(FrmName,FrmEmpId,ToName) values (@FrmName,@FrmEmpId,@ToName)";
SqlCommand cmd= new SqlCommand(query,con);
cmd.Parameters.AddWithValue(@"Transstat", "Raised");
cmd.Parameters.AddWithValue(@"AssetNo", txtAsset.Text);
cmd.Parameters.AddWithValue(@"FrmName", txtfrm.Text);
cmd.Parameters.AddWithValue(@"FrmEmpId", Global.transferorid);
cmd.Parameters.AddWithValue(@"ToName", txtName.Text);
cmd.ExecuteNonQuery();
cmd.Dispose();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.