gpt4 book ai didi

sql-server - Insert OUTPUT Insert.id to another table in multiple values insert

转载 作者:行者123 更新时间:2023-12-02 15:30:51 26 4
gpt4 key购买 nike

为了简单起见,假设我有两个表

用户表(id,email)

用户日志表(id, date)

无论 id 被插入到 user 表中,相同的 id 也应该被插入到 user_log 表中,否则事务应该失败。

我该怎么做

BEGIN TRANSACTION

INSERT into user(id, email) OUTPUT Inserted.id (1, 'a@x.com', 'x'), (2, 'b@x.com', 'y')

// I also want to be able to do
INSERT into user_log(id, date) values(1, date), (2, date)

COMMIT TRANSACTION

最佳答案

您可以将输出直接插入到 user_log 表中:

BEGIN TRANSACTION

INSERT INTO [User] (ID, Email)
OUTPUT inserted.id, CURRENT_TIMESTAMP INTO user_log(id, date)
VALUES (1, 'a@x.com'), (2, 'b@x.com');

COMMIT TRANSACTION

Example on SQL Fiddle


如果您需要返回 ID,您可以添加第二个 OUTPUT 子句:

BEGIN TRANSACTION

INSERT INTO [User] (ID, Email)
OUTPUT inserted.id, CURRENT_TIMESTAMP INTO user_log(id, date)
OUTPUT inserted.id
VALUES (1, 'a@x.com'), (2, 'b@x.com');

COMMIT TRANSACTION

关于sql-server - Insert OUTPUT Insert.id to another table in multiple values insert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26400301/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com