选择插入中的SQL Server子查询

时间:2016-03-04 13:33:07

标签: sql sql-insert sql-server-2014

有关使此工作的任何建议吗?语法上它是正确的,并且各个子查询返回单个结果,但是当组合时,子查询不会将结果返回到insert语句。基本上我正试图将这些记录插入到表中,如果它们在视图中不存在。

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

1 个答案:

答案 0 :(得分:4)

我猜这个OUTPUT条款有用(我还没有用@@ROWCOUNT,但看起来没问题。)

您不需要FROM条款 - 至少不需要整个表格。我可能会建议:

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