简体   繁体   中英

Get dynamic variable for SQL insert

I have a query like this:

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 is not yet defined, but it should be equal to the id that comes from the inner SELECT statement from foo .

Just dont use values, use a select

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
)

If there is no table for the sp_id to be in, you could get rid of that where caluse and move the sub select up like this:

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
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)

Listing column names is not necessary unless their ordinal position is different or you are only applying this to certain columns, not all of them

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM