简体   繁体   中英

SQL Server Sub query in select insert

Any suggestions on getting this to work? syntactically it is correct, and the individual sub-queries return a single result, however when combined the sub-queries do not return results to the insert statement. Essentially i am trying to insert these records into the table if they do not exist in the view.

INSERT INTO PRG_T_BLK_MDL (BLK_ID, MDL_ID, GW, VE)
    OUTPUT @@ROWCOUNT AS RC
    SELECT (SELECT ID FROM PRG_T_BLK WHERE NAME=1),
            (SELECT ID FROM PRG_T_MDL WHERE NAME='A'), 3500, 'AX'
    FROM PRG_V_BLK_MDL
    WHERE NOT EXISTS(SELECT 1 FROM PRG_V_BLK_MDL WHERE BLK=1 AND MDL='A' AND VER='AX')

I am guessing that the OUTPUT clause works (I haven't used it with @@ROWCOUNT , but it seems ok).

You don't need a FROM clause -- at least not with the entire table. I might suggest:

INSERT INTO PRG_T_BLK_MDL (BLK_ID, MDL_ID, GW, VE)
    OUTPUT @@ROWCOUNT AS RC
    SELECT (SELECT ID FROM PRG_T_BLK WHERE NAME = t.BLK),
            (SELECT ID FROM PRG_T_MDL WHERE NAME = t.MDL), 3500, t.ver
    FROM (SELECT 1 as BLK, 'A' as MDL, 'AX' as ver) t
    WHERE NOT EXISTS (SELECT 1
                      FROM PRG_V_BLK_MDL v
                      WHERE v.BLK = t.BLK AND v.MDL = t.MDL AND v.ver = t.ver);

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