SELECT INTO T-SQL 中的表变量

SELECT INTO a table variable in T-SQL(SELECT INTO T-SQL 中的表变量)
本文介绍了SELECT INTO T-SQL 中的表变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个复杂的 SELECT 查询,我想从中插入所有行到一个表变量中,但 T-SQL 不允许这样做.

Got a complex SELECT query, from which I would like to insert all rows into a table variable, but T-SQL doesn't allow it.

同样,您不能将表变量用于 SELECT INTO 或 INSERT EXEC 查询.http://odetocode.com/Articles/365.aspx

Along the same lines, you cannot use a table variable with SELECT INTO or INSERT EXEC queries. http://odetocode.com/Articles/365.aspx

简短示例:

declare @userData TABLE(
                        name varchar(30) NOT NULL,
                        oldlocation varchar(30) NOT NULL
                       )

SELECT name, location
INTO @userData
FROM myTable
    INNER JOIN otherTable ON ...
WHERE age > 30

表变量中的数据稍后将用于将其插入/更新回不同的表(主要是相同数据的副本,并进行少量更新).这样做的目的是让脚本比直接在正确的表中执行 SELECT INTO 更具可读性和更容易定制.性能不是问题,因为 rowcount 相当小,并且仅在需要时手动运行.
...或者只是告诉我我是否做错了.

The data in the table variable would be later used to insert/update it back into different tables (mostly copy of the same data with minor updates). The goal of this would be to simply make the script a bit more readable and more easily customisable than doing the SELECT INTO directly into the right tables. Performance is not an issue, as the rowcount is fairly small and it's only manually run when needed.
...or just tell me if I'm doing it all wrong.

推荐答案

试试这样的:

DECLARE @userData TABLE(
    name varchar(30) NOT NULL,
    oldlocation varchar(30) NOT NULL
);

INSERT INTO @userData (name, oldlocation)
SELECT name, location FROM myTable
INNER JOIN otherTable ON ...
WHERE age > 30;

这篇关于SELECT INTO T-SQL 中的表变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)