我有以下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条?
答案 0 :(得分:4)
您可以使用 UNION ALL 组合2条选择语句:
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;