简体   繁体   English

用union插入表变量

[英]Insert into table variable with union

I've got a table variable that I'm wanting to insert a union query. 我有一个表变量,我想插入一个联合查询。 The union query runs fine, but I can't seem to get the insert to work (syntax error) 联合查询运行正常,但是我似乎无法使插入工作(语法错误)

INSERT INTO @table

(a,
b,
c,
d)

VALUES

(SELECT
       a,
       b,
       c,
       d 
FROM table1

UNION

SELECT
       a,
       b,
       c,
       d 
FROM table2)

Should this be working? 这应该工作吗? I can post my real code if there is an issue elsewhere! 如果其他地方有问题,我可以发布真实代码!

I'm getting a syntax error on the first SELECT 我在第一个SELECT上遇到语法错误

INSERT INTO @table(a,b,c,d)
SELECT  a,b,c,d 
FROM   table1

UNION

SELECT a,b,c,d 
FROM table2

You do not need to use the Values clause when Inserting data using SELECT statement. 使用SELECT语句插入数据时,无需使用Values子句。 Therefore I have removed the VALUES bit from it and just simply doing a UNION of rows being returned from both SELECT queries. 因此,我从中删除了VALUES位,只是简单地对两个SELECT查询返回的行进行了UNION处理。

Sql server supports the syntax for INSERT statement like SQL Server支持INSERT语句的语法,例如

INSERT INTO Table_Name(Col1, COl2. Col3...)
SELECT Col1, COl2. Col3...
FROM Other_Table_Name

This will insert that result set returned by the select statement into target table. 这会将select语句返回的结果集插入目标表。 In your case the Result is a UNION of two selects therefore it is not any different from a single select. 在您的情况下,结果是两个选择的UNION,因此与单个选择没有什么不同。

"VALUES" isn't needed in this case 在这种情况下,不需要“ VALUES”

INSERT INTO @table (a, b, c, d)
SELECT a, b, c, d FROM table1 
UNION 
SELECT a, b, c, d FROM table2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM