带有" NOT EXIST"的SQL插入语句基于第二列

时间:2016-06-01 02:12:15

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

我有这个功能正常的插入语句,但只有在DEPTCODE' 725' ...任何想法的NUMBER不存在时才需要插入SL_PROD?

INSERT INTO SL_PROD (NUMBER, DEPTCODE, DISP_SEQ, LU_BY, LU_ON)
SELECT ST_EXTRA.NUMBER, '725', '1', 'IN', getdate()
FROM ST_EXTRA
INNER JOIN STOCK ON STOCK.NUMBER = ST_EXTRA.NUMBER
WHERE UNITS > 0 AND datename(m,colEMAILDATE) = datename(m, DATEADD(m, -1, getdate()))

1 个答案:

答案 0 :(得分:1)

使用not exists

INSERT INTO SL_PROD (NUMBER, DEPTCODE, DISP_SEQ, LU_BY, LU_ON)
SELECT ST_EXTRA.NUMBER, '725', '1', 'IN', getdate()
FROM ST_EXTRA
INNER JOIN STOCK ON STOCK.NUMBER = ST_EXTRA.NUMBER
WHERE UNITS > 0 
AND datename(m,colEMAILDATE) = datename(m, DATEADD(m, -1, getdate()))
AND NOT EXISTS (select 1 from sl_prod 
                where number = st_extra.number
                and deptcode = '725')