在 T-SQL 中选择一个表变量 - SELECT INTO a table variable in 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 查询,我想从中插入所有行到表变量中,但 T-SQL 不允许。

Along the same lines, you cannot use a table variable with SELECT INTO or INSERT EXEC queries.同样,您不能在 SELECT INTO 或 INSERT EXEC 查询中使用表变量。 http://odetocode.com/Articles/365.aspx http://odetocode.com/Articles/365.aspx

Short example:简短示例:

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

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.这样做的目的是简单地使脚本比直接在正确的表中执行SELECT INTO更具可读性和更容易定制。 Performance is not an issue, as the rowcount is fairly small and it's only manually run when needed.性能不是问题,因为行rowcount相当小,并且仅在需要时手动运行。
...or just tell me if I'm doing it all wrong. ……或者只是告诉我是不是我做错了。


解决方案:

参考一: https://stackoom.com/question/G6V6
参考二: SELECT INTO a table variable in T-SQL
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章