我收到此错误
列名称ID无效。
有什么问题?
private void btnInsert_Click(object sender, EventArgs e)
{
connection.Open();
try
{
string query2 = "INSERT INTO Suppliers (SupName) OUTPUT
Inserted.Id VALUES (@SupName)";
SqlCommand cmd2 = new SqlCommand(query2, connection);
cmd2.Parameters.AddWithValue("@SupName", txtCname.Text);
int supID = (int)cmd2.ExecuteScalar();
//cmd2.Parameters.Clear();
string query3 = "INSERT INTO SupplierContacts (SupConAddress,
SupConCity, AffiliationId, SupplierId)
VALUES (@SupConAddress, @SupConCity,
@AffiliationId, @SupplierId)";
SqlCommand cmd3 = new SqlCommand(query3, connection);
cmd3.Parameters.AddWithValue("@SupConAddress", txtCaddress.Text);
cmd3.Parameters.AddWithValue("@SupConCity", txtCcity.Text);
cmd3.Parameters.AddWithValue("@AffiliationId", aff.AffilitationId);
cmd3.Parameters.AddWithValue("@SupplierId", supID);
// cmd3.Parameters.Clear();
MessageBox.Show("Data Inserted");
}
catch(SqlException ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
}
答案 0 :(得分:0)
您正在尝试使用OUTPUT
子句。但是,正确的语法需要表名。在T-SQL中,这可能写成:
DECLARE @SupplierIds TABLE (SupplierId int);
INSERT INTO Suppliers (SupName)
OUTPUT Inserted.SupplierId INTO @SupplierIds
VALUES (@SupName);
这就是将SupplierId
的新值放入表格SupplierIds
。然后,您可以通过参考表来检索该值:
SELECT *
FROM @SupplierIds;
但是,您无法跨多个查询引用该表。
我的建议是你使用多个语句运行整个脚本。或者(我可能会做的)编写一个存储过程,其中包含插入两个表的所有逻辑。