0

我正在尝试使用参数插入查询静态填充子表中的外键值我得到了成功但是当我尝试动态执行它时它不起作用

我的父表是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();

当我在第二个查询中给出一个硬代码值时它在哪里工作但如何动态地做我想每个人都理解我的问题请帮助谢谢

4

1 回答 1

1

尝试一下:

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();
于 2012-07-13T07:33:49.813 回答