我应该执行每个查询还是单个查询?

Should I execute every query or single query?

我正在尝试使用 ado.net 将多条记录插入到 table,并打印 id 已插入。

我的代码是这样的:

List<string> listQuery = new List<string>()
{
    "INSERT INTO Students (Name) VALUES ('student1');SELECT @@Identity;",
    "INSERT INTO Students (Name) VALUES ('student2');SELECT @@Identity;",
    "INSERT INTO Students (Name) VALUES ('student3');SELECT @@Identity;",
};
using (SqlConnection connection = new SqlConnection(_connectionString))
{
    try
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand())
        {
            command.Connection = connection;

            foreach (var myQuery in listQuery)
            {
                command.CommandText = myQuery;
                int id = Convert.ToInt32((decimal)command.ExecuteScalar());
                Console.WriteLine("Inserted: " + id);
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        //Close and dispose
        connection.Close();
    }
}

我在想,我是否应该像这样执行每个命令?或者连接所有查询并只执行一次?

如果我应该执行一次。我怎样才能插入所有 id 条记录?

您可以使用 OUTPUT 子句来 return 身份 id

INSERT INTO Students (Name)
OUTPUT  INSERTED.id
VALUES ('student1'), ('student2'), ('student3');

不要这样,也不要在任何循环中调用数据库。

为了解决您的问题,您应该编写将 DataTable 作为学生列表输入的存储过程(tutorial) or use JSON string 作为输入。在该存储过程中,您使用 OUTPUT 子句检索 ID: OUTPUT INSERTED.id . 在 C# 代码中,您只需要 ExecuteReader 即可获取所有 id。