我正在尝试使用参数化插入查询来填充子表中的外键值 静态地我获得成功,但当我试图动态地做它不起作用
我的父表是Customer
custId(pk),CustName,contact是那里的字段
和子表格为_order
orderId(pk),item,qauntity,cust_Id(fk)是filelds
我在c#中插入的代码是:
SqlCommand scmd = new SqlCommand("insert into Customer (custname,contact)values(@custname,@contact)", conn);
scmd.Parameters.AddWithValue("@custname", cusname.Text);
scmd.Parameters.AddWithValue("@contact", contact.Text);
scmd.ExecuteNonQuery();
SqlCommand scmd1 = new SqlCommand("insert into _order (item,qauntity,cust_Id) select @item,@qauntity,custId from Customer where custId= @custId", conn);
scmd1.Parameters.AddWithValue("@item", item.Text);
scmd1.Parameters.AddWithValue("@qauntity", qauntity.Text);
scmd1.ExecuteNonQuery();
当我在第二个查询中给出一个硬代码值,它在哪个条件下工作但是如何动态地执行它 我想大家都明白我的问题请帮帮忙 感谢
答案 0 :(得分:0)
试一试:
SqlCommand scmd = new SqlCommand("insert into Customer (custname,contact)values(@custname,@contact); SELECT SCOPE_IDENTITY()", conn);
scmd.Parameters.AddWithValue("@custname", cusname.Text);
scmd.Parameters.AddWithValue("@contact", contact.Text);
int custId = Convert.ToInt32(scmd.ExecuteScalar());
SqlCommand scmd1 = new SqlCommand("insert into _order (item,qauntity,cust_Id) VALUES(@item,@qauntity,@custId)", conn);
scmd1.Parameters.AddWithValue("@item", item.Text);
scmd1.Parameters.AddWithValue("@qauntity", qauntity.Text);
scmd1.Parameters.AddWithValue("@custId", custId);
scmd1.ExecuteNonQuery();