这个问题在这里已有答案:
我有以下SQL脚本(简化):
DECLARE @table TABLE (col1 int, col2 int, col3 int);
INSERT INTO @table
SELECT id, 1, amount
FROM transactions
WHERE customerId = 10;
INSERT INTO @table
SELECT TOP(1) id, 5, amount - charges
FROM transactions
WHERE customerId = 10
ORDER BY id DESC;
在上面的例子中,我首先在表变量中插入一些记录。然后我使用最后一条记录插入一条额外的记录。
是否可以将2个语句合并为1个?
您可以使用UNION ALL组合2个select语句:
INSERT INTO @table
SELECT id, 1, amount
FROM transactions
WHERE customerId = 10;
UNION ALL
SELECT TOP(1) id, 5, amount - charges
FROM transactions
WHERE customerId = 10
ORDER BY id DESC;