我有这个功能正常的插入语句,但只有在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()))
答案 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')