将数据插入两个表时 =>错误:“列名 Id 无效”

本文关键字:错误 列名 无效 Id 插入 数据 两个 | 更新日期: 2023-09-27 18:33:04

我收到此错误

列名 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();
        }

将数据插入两个表时 =>错误:“列名 Id 无效”

您正在尝试使用 OUTPUT 子句。 但是,正确的语法需要表名。 在 T-SQL 中,这可能写为:

DECLARE @SupplierIds TABLE (SupplierId int);
INSERT INTO Suppliers (SupName)
    OUTPUT Inserted.SupplierId INTO @SupplierIds
    VALUES (@SupName);

这是说将SupplierId的新值放入表中SupplierIds。 然后,您可以通过引用该表来检索该值:

SELECT *
FROM @SupplierIds;

但是,不能跨多个查询引用该表。

我的建议是使用多个语句运行整个脚本。 或者(我可能会做的)编写一个存储过程,其中包含插入到两个表中的所有逻辑。