我正在寻找一种方法来更新指定的SQL表(tr__Transaction
)上的一些值,并将一些值插入到历史表(tr_History
)中,同时(在单个查询中)描述更新的内容(字符串值),而不使用循环和触发器.
这不是我设计的数据库,但它是我正在处理的现有数据库.例如,我正在用tr_ShippingMethodId
列中的新值更新(1,3,5)集中的现有记录.
更新了3行,现在我想向这tr_History
个表中插入与我的示例查询相对应的新记录.
以下是我的样例代码:
DECLARE @tr__Transaction TABLE (tr_Id int, tr_ShippingMethodId int) -- table with transactions (online sale)
INSERT INTO @tr__Transaction (tr_Id, tr_ShippingMethodId)
VALUES (1, 2), (2, 2), (3, 9), (4, 8), (5, 0)
DECLARE @tr_History TABLE
(
th_Id INT,
th_TransId INT,
th_Time DATETIME,
th_Entry NVARCHAR(255)
) -- table with history log (what changed made on transaction)
DECLARE @TrIdsToUpdate TABLE (trIdToUpdate int) -- table with ids to update
INSERT INTO @TrIdsToUpdate VALUES (1, 3, 5)
UPDATE @tr__Transaction
SET tr_ShippingMethodId = 99
WHERE tr_Id IN (SELECT trIdToUpdate FROM @TrIdsToUpdate)
INSERT INTO @tr_History (th_Id, th_TransId, th_Time, th_Entry)
VALUES (spGetId(tr_History), 1, GETDATE(), 'Record 1 changed shipping method from 2 to 99')
INSERT INTO @tr_History (th_Id, th_TransId, th_Time, th_Entry)
VALUES (spGetId(tr_History), 3, GETDATE(), 'Record 3 changed shipping method from 9 to 99')
INSERT INTO @tr_History (th_Id, th_TransId, th_Time, th_Entry)
VALUES (spGetId(tr_History), 5, GETDATE(), 'Record 5 changed shipping method from 0 to 99')
在这个查询中,我必须使用spGetId(tr_History)
存储过程,它返回一个要插入的空闲ID(这是它最初设计的方式).
我还使用了3个INSERT
命令来演示我想要实现的目标,但是使用@TrIdsToUpdate
表和单个INSERT
.
有什么建议要怎么做吗?