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;
相关文章