获取用于SQL插入的动态变量

时间:2018-09-06 18:11:16

标签: sql sql-server tsql

我有这样的查询:

INSERT INTO my_table
VALUES (SPECIAL_ID, 62, 0, 1, -1, NULL, NULL, -1)
WHERE sp_id IN (SELECT id = SPECIAL_ID
                FROM foo
                WHERE lock IS NULL)

SPECIAL_ID尚未定义,但应等于id内部SELECT语句中的foo

2 个答案:

答案 0 :(得分:2)

只要不使用值,请使用选择

INSERT INTO my_table (need To declare list of column names for table insert)
Select SPECIAL_ID, 62, 0, 1, -1, NULL, NULL, -1
From Table
WHERE sp_id IN(
    SELECT id = SPECIAL_ID
    FROM foo
    WHERE lock IS NULL
)

如果没有可用于sp_id的表,则可以摆脱caluse所在的位置,并向上移动子选择,如下所示:

INSERT INTO my_table (need To declare list of column names for table insert)
Select SPECIAL_ID, 62, 0, 1, -1, NULL, NULL, -1    
FROM foo
WHERE lock IS NULL

答案 1 :(得分:0)

SELECT SPECIAL_ID, 62, 0, 1, -1, NULL, NULL, -1 
INTO my_table 
FROM your_source_table 
WHERE sp_id in (SELECT id = SPECIAL_ID
               FROM foo
               WHERE lock IS NULL)

除非列的顺序位置不同,或者您仅将其应用于某些列而不是全部列,否则不必列出列名