使用WHERE IN子句INSERT INTO

时间:2016-08-20 01:22:48

标签: sql sql-server sql-server-2008 insert

INSERT INTO dbo.ASTMListCustom ([ASTMID], [EDMID], [Distance], [Selected])
    SELECT 
        ASTMID, 'HWG - VT', 1, 1
    FROM   
        dbo.ASTMListCustom
    WHERE 
        ASTMID IN ( 15, 21, 22, 23, 25, 38, 63, 72, 73, 74, 75, 82, 83, 125, 130, 163, 165, 182, 206, 207, 208, 214, 217, 250, 255, 256, 257, 264, 266, 299, 317, 342, 348, 349, 350, 357, 381, 382, 391, 392, 397, 398, 422, 448, 450, 451, 466, 481, 9, 12, 17, 18, 26, 61, 62, 67, 68, 69, 70, 77, 85, 92, 93, 94, 95, 126, 128, 129, 136, 137, 145, 146, 153, 154, 179, 203, 211, 213, 219, 221, 237, 253, 254, 261, 262, 301, 326, 327, 328, 329, 343, 346, 353, 368, 369, 386, 394, 436)

我正在尝试为每个ASTMID插入一行,但最终会复制每个ASTMID的行数,并且重复项与您插入的行数相同。

1 个答案:

答案 0 :(得分:1)

您的ASTMListCustom表似乎在列表中的ASTMID上有重复的行。您可以通过向GROUP BY添加SELECT来解决此问题:

INSERT INTO dbo.ASTMListCustom
           ([ASTMID]
           ,[EDMID]
           ,[Distance]
           ,[Selected])    
SELECT     ASTMID
           ,'HWG - VT'
           ,1
           ,1
FROM   dbo.ASTMListCustom
WHERE ASTMID IN ( 15, ... )
GROUP BY ASTMID