使用联合插入表变量 [英] Insert into table variable with union

查看:27
本文介绍了使用联合插入表变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要插入联合查询的表变量.联合查询运行良好,但我似乎无法让插入工作(语法错误)

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!

我在第一个 SELECT 时遇到语法错误

I'm getting a syntax error on the first SELECT

推荐答案

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

UNION

SELECT a,b,c,d 
FROM table2

使用 SELECT 语句插入数据时不需要使用 Values 子句.因此,我已经从中删除了 VALUES 位,只是简单地对从两个 SELECT 查询返回的行进行 UNION 操作.

You do not need to use the Values clause when Inserting data using SELECT statement. Therefore I have removed the VALUES bit from it and just simply doing a UNION of rows being returned from both SELECT queries.

Sql server 支持 INSERT 语句的语法,如

Sql server supports the syntax for INSERT statement like

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

这会将 select 语句返回的结果集插入到目标表中.在您的情况下,结果是两个选择的联合,因此它与单个选择没有任何不同.

This will insert that result set returned by the select statement into target table. In your case the Result is a UNION of two selects therefore it is not any different from a single select.

这篇关于使用联合插入表变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆