是否可以合并2个SELECT语句以在INSERT INTO语句中使用?

时间:2019-03-30 03:56:50

标签: sql sql-server sql-server-2017

我有以下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条?

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;