在 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章