我想检查" refno"已存在于Tbldelivery表中,如果" refno"存在,然后它将插入" Tbldeliverydetails"因为" refno"是第一个表中的主键。我检查条件的地方?
这是我在C#中编写的代码:
protected void btndlysave_Click(object sender, EventArgs e)
{
SqlConnection SqlCon = new SqlConnection("server=(local);Initial Catalog=TestDB;Integrated Security=SSPI;");
try
{
SqlCon.Open();
SqlCommand cmd = new SqlCommand("insert into Tbldelivery (refno,deliverdate,requestby,projectcode) values
(@refno,@deliverdate,@requestby,@projectcode) WHERE not exists (select refno from Tblinkdelivery where refno = @refno)", SqlCon);
cmd.CommandType = CommandType.Text;
if ( need check here)
cmd.Parameters.AddWithValue("@refno", txtdelrefno.Text.Trim());
cmd.Parameters.AddWithValue("@deliverdate", txtdeldate.Text.Trim());
cmd.Parameters.AddWithValue("@requestby", txtdelreq.Text.Trim());
cmd.Parameters.AddWithValue("@projectcode", ddlprojcode.Text.Trim());
}
else
{
SqlCommand cmd2 = new SqlCommand("insert into Tbldeliverdetails (refno,printercode,inkcode,quantity,price,notes) values (@refno,@printercode,@inkcode,@quantity,@price,@notes)", SqlCon);
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.AddWithValue("@refno", txtdelrefno.Text.Trim());
cmd2.Parameters.AddWithValue("@printercode", ddldelprcode.Text.Trim());
cmd2.Parameters.AddWithValue("@inkcode", ddlinkcode.Text.Trim());
cmd2.Parameters.AddWithValue("@quantity", txtdelqty.Text.Trim());
cmd2.Parameters.AddWithValue("@price", txtdelprice.Text.Trim());
cmd2.Parameters.AddWithValue("@notes", txtdelnotes.Text.Trim());
int val1 = cmd.ExecuteNonQuery();
int val2 = cmd2.ExecuteNonQuery();
}
finally
{
SqlCon.Close();
}
}
答案 0 :(得分:1)
我认为首先你需要安排你的代码。
在button click
事件中写下所有内容并不是很好。如果您可以将业务逻辑分开并将其单独放置,那就更好了。
尝试这样的事情。
您可以创建处理数据访问的Data Access
类。
在您的数据访问类
public SqlConnection OpenConnection()
{
try
{
var conn = new SqlConnection(“xxx”);
conn.Open();
return conn;
}
catch (Exception ex)
{
//log the exception
return null;
}
}
YourFunction(parameters)
{
var conn = OpenConnection();
if(conn != null)
{
//your code
// you can do something similar as JeremyK explained here
}
}
点击按钮
protected void btndlysave_Click(object sender, EventArgs e)
{
//CHECK THE PARAMETERS AND PASS
//DataAccess. YourFunction(parameters)
}
答案 1 :(得分:0)
您查询该表并查看它是否存在。
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand sqlCommand =
new SqlCommand("SELECT * FROM dbo.Tbldelivery WHERE refno=@refno",
connection);
sqlCommand.Parameters.Add("@refno", System.Data.SqlDbType.VarChar);
sqlCommand.Parameters["@refno"].Value = refnoValue;
SqlDataReader reader = sqlCommand.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
// refno exists
}
else
{
// refno does not exist
}
}