如何在单个查询中执行多个Insert语句?

时间:2018-12-30 05:18:14

标签: c# sql ssms

我正在制作一个表单,其中用户回答一些问题以定价。我的问题是我无法将问题中的数据存储到多个sql表中。

我尝试将另一个表插入sql命令(如下所示),并且尝试制作另一个sql命令,该命令基本上说相同的东西但名称不同,但是将名称和电话号码分为第一个和日期创建日期并将其放入第二个表中,但是只运行第一个sql命令,然后停止,因此数据永远不会存储到第二个表中

private void AddPhBttn_Click(object sender, RoutedEventArgs e)
    {
        SqlConnection furniture = new SqlConnection("Data Source=LAPTOP-F4QFMPFD\\MSSQLSERVER1;Initial Catalog=Furniture;Integrated Security=True");



        furniture.Open();
        SqlCommand add = new SqlCommand("insert into Customers(Name, Phone) PriceHold(DateCreated, PickUpDate) values ('" + nameTxtBox.Text + "', '" + phoneTxtbox.Text + "', '" + dateTxtBox.Text + "', '" + puDateTxtBox.Text + "')", furniture);

        int i = add.ExecuteNonQuery();
        if (i != 0)
        {
            MessageBox.Show("saved");
        }
        else MessageBox.Show("error");
    }

3 个答案:

答案 0 :(得分:1)

正如@Caius Jard所说,临时查询无法做到这一点。

那么有什么选择呢?

步骤1::在数据库中创建一个Stored Procedure

CREATE PROCEDURE usp_InsertData
@Name NVARCHAR(200),
@Phone NVARCHAR(100),
@DateCreated Date,
@PickUpDate Date
AS
BEGIN
    SET NOCOUNT ON;
    INSERT INTO Customers(Name, Phone) VALUES (@Name,@Phone)

    INSERT INTO PriceHold(DateCreated, PickUpDate) VALUES (@DateCreated,@PickUpDate) 
END

步骤2:使用C#代码在上述存储过程中调用:

private void AddPhBttn_Click(object sender, RoutedEventArgs e)
{
     var furniture = new SqlConnection("Data Source=LAPTOP-F4QFMPFD\\MSSQLSERVER1;Initial Catalog=Furniture;Integrated Security=True");

     SqlCommand add = new SqlCommand("usp_InsertData", furniture);
     add.CommandType = System.Data.CommandType.StoredProcedure;

     add.Parameters.AddWithValue("@Name", nameTxtBox.Text);
     add.Parameters.AddWithValue("@Phone", phoneTxtbox.Text);
     add.Parameters.AddWithValue("@DateCreated", dateTxtBox.Text);
     add.Parameters.AddWithValue("@PickUpDate", puDateTxtBox.Text);
     furniture.Open();

     int i = add.ExecuteNonQuery();

     if (i != 0)
     {
          MessageBox.Show("saved");
     }
     else
     {
         MessageBox.Show("error");
     }
     furniture.Dispose();

}

答案 1 :(得分:0)

您无法在SQL中执行此操作

INSERT INTO 
  myfirsttable(column1, column2)
  mysecondtable(column3, column4, column5)
VALUES(value1, value2, value3, value4)

解决了语法错误。插入中只能出现一个表。插入的值数必须与列数

匹配

如果要插入两个表,请从您的C#代码中运行两个单独的插入

最后,请长时间阅读http://bobby-tables.com-您的代码目前非常不安全,尽管现在这可能并不重要,因为它只是一些小型测试应用程序,所以最好避免走上包含以下内容的学习道路用这种方式编码。作为一名招聘人员,我拒绝了许多这样编写SQL的求职者,而且我永远也不会雇用向我展示这种风格的人

答案 2 :(得分:0)

使用多个表中的数据时,如果要确保全部插入/更新/删除成功完成或全部都不会应用于您的数据为确保数据完整性,请使用事务。我认为SqlTransaction是您所追求的。阅读here

对于您的特定情况,这是一种可能性:

private void AddPhBttn_Click(object sender, RoutedEventArgs e)
{
    // Necessary input validation to collect and data from input fields. Good practice to avoid SQL injection.
    AddFurniture(nameTxtBox.Text, phoneTxtbox.Text, dateTxtBox.Text, puDateTxtBox.Text);
}

private void AddFurniture(string name, string phoneNumber, string createdDate, string pickupDate)
{
    string connectionString = "Data Source=LAPTOP-F4QFMPFD\\MSSQLSERVER1;Initial Catalog=Furniture;Integrated Security=True"; // This should ideally come from some configuration.
    using(SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction = connection.BeginTransaction("Add Furniture");
        command.Connection = connection;
        command.Transaction = transaction;

        try
        {
             connection.Open();
            command.CommandText = $"insert into Customers (Name, Phone) values ({name}, {phoneNumber});";
            command.ExecuteNonQuery();
            command.CommandText = $"insert into PriceHold (DateCreated, PickUpDate) values ({createdDate}, {pickupDate});";
            command.ExecuteNonQuery();

            // Try to commit to database.
            // Both the above queries are executed at this point. If any one of them fails, 'transaction' will throw an exception.
            transaction.Commit();
        }
        catch (Exception ex1)
        {
            // Considering the statements executed using the 'transaction' for this 'connection',
            // one of the insert operations have clearly failed.
            // Attempt to roll back the change which was applied.
            MessageBox.Show($"Insert failed. Trying to roll back {ex1.Message}");
            try
            {
                transaction.RollBack();
            }
            catch (Exception ex2)
            {
                // Rollback also failed. Possible data integrity issue. Handle it in your application.
                MessageBox.Show($"Roll back failed. {ex2.Message}");
            }
         }
     }
}