如何在插入之前检查值是否存在?
INSERT INTO DeliveryOrder (ContactName, ContactID) VALUES ('Andy', (SELECT ContactID FROM Contact WHERE ContactName = 'Andy'))
我想在插入记录之前验证ContactID是否存在。
尝试以下但不工作:
INSERT INTO DeliveryOrder (ContactName, ContactID) VALUES ('Andy', (SELECT ContactID FROM Contact WHERE ContactName = 'Andy')) WHERE IF Exists (SELECT ContactID FROM Contact WHERE ContactName = 'Andy')
答案 0 :(得分:2)
INSERT INTO DeliveryOrder (ContactName, ContactID)
select 'Andy', ContactID
from Contact
WHERE ContactName = 'Andy'
答案 1 :(得分:0)
这会对你有所帮助
IF EXISTS (SELECT ContactID
FROM Contact c
WHERE
c.ContactName ='Andy'
)
Insert Into DeliveryOrder (ContactName, ContactID)
VALUES ('Andy', (SELECT top 1 ContactID FROM Contact WHERE ContactName = 'Andy'))
试试这个