同时添加主从数据

问题描述 投票:0回答:1

使用 SQL Server 2022,

INSERT INTO ... OUTPUT.Inserted.* VALUES ...
可以获取插入的项目。然后语句可以将数据插入一张或两张表(具有相同的表结构)。

是否可以向不同表结构的多表插入数据?

CREATE TABLE tb_Master
(
    Id INT IDENTITY(1,1) PRIMARY KEY,
    [Master] VARCHAR(50)
)

CREATE TABLE tb_Slave
(
    Id INT IDENTITY(1,1) PRIMARY KEY,
    ParentId INT NOT NULL, --tb_Master.Id
    [Slave] VARCHAR(50)
)

C# 实体模型:

internal class MasterMdl
{
    public int Id { get; set; }

    public string Master { get; set; }

    public IEnumerable<SlaveMdl> Slaves { get; set; }
}

internal class SlaveMdl
{
    public int Id { get; set; }
    public int ParentId { get; set; }

    public string Slave { get; set; }
}

在C#中,创建要插入的数据:

var list = new List<MasterMdl>();

for (int i = 0; i < 10; i++)
{
    var m = new MasterMdl()
    {
        Master = $"Master {i}",
    };

    SlaveMdl[] slaves = new SlaveMdl[5];

    for (int j = 0; j < 5; j++)
    {
        slaves[j] = new SlaveMdl()
        {
            Slave = $"Slave {j}"
        };
    }

    m.Slaves = slaves;

    list.Add(m);
}

更新:我的示例 C# 代码

using var masterCmd = await _dbConnectionContext.CreateCommand<TUserData>(mastSQL, masterParameterItems, token, false);

var reader = await masterCmd.ExecuteReaderAsync(token);

var allSlaves = new List<TSlave>();

var handler = statement.Context.GetSlaveHandler;
var parentId = statement.Context.ParentId;

await reader.ReadAsync(token);

foreach (var data in userData)
{
    var slaves = handler.Invoke(data);
    var id = reader[0];

    foreach (var slave in slaves)
    {
        (parentId as IPropertyValue<TSlave>).SetValue(slave, id); 
    }
                    
    allSlaves.AddRange(slaves);

    await reader.ReadAsync(token);
}

reader.Close();

using var slaveCmd = await _dbConnectionContext.CreateCommand<TSlave>(slaveSQL, slaveParameterItems, token, false);
var ret = await slaveCmd.ExecuteNonQueryAsync(token);

await _dbConnectionContext.Commit(token);

在 SQL Server 中将多个值插入到多个表中 https://www.geeksforgeeks.org/insert-multiple-values-into-multiple-tables-using-a-single-statement-in-sql-server/

CREATE TABLE GeekTable1 (
  Id1 INT,
  Name1 VARCHAR(200),
  City1 VARCHAR(200)
);

CREATE TABLE GeekTable2 (
  Id2 INT,
  Name2 VARCHAR(200),
  City2 VARCHAR(200)
);

INSERT INTO GeekTable1 (Id1, Name1, City1)
OUTPUT inserted.Id1, inserted.Name1, inserted.City1
INTO GeekTable2
VALUES (1, 'Komal', 'Delhi'),
       (2, 'Khushi', 'Noida');


SELECT * FROM GeekTable1;
GO
SELECT * FROM GeekTable2;
GO
c# sql sql-server
1个回答
0
投票

在 SQL 中,您可以使用事务来确保两个表都已填充,或者都没有。
这是一个例子

declare @newid int;

begin try
      begin tran

      insert into tb_Master (Master) values ('hello world');
      set @newid = Scope_identity();

      insert into tb_slave (ParentId, Slave) values (@newid, 'good morning');

      commit tran
end try
begin catch
      rollback tran
      throw 51000, 'something went wrong', 1
end catch;

        
select * from tb_Master;
select * from tb_Slave;

另请参阅 this dbFiddle 其中显示了发生错误时会发生的情况

© www.soinside.com 2019 - 2024. All rights reserved.