I have an insert statement that I can’t get to work the way I want it to. It’s on a vb.net page. This is on a VB.net page and I’m using SQL Server 2005 for my database.
Dim strSQL As String = "IF NOT EXISTS
(SELECT Title From Picklist)
BEGIN INSERT INTO Picklist (Title, Data)
VALUES (@Title, @Data);
INSERT INTO Marketing
(ProductID, MarketingTypeID, MarketingTitle, MarketingData)
VALUES (@ProductID, 9, 'Video', scope_identity()) END"
I don’t get an error and nothing gets inserted into the database. If I try putting the END at the end of the first INSERT statement then I get an error saying that MarketingData is NULL and cannot be inserted.
But if I take out the IF NOT EXISTS from the statement, everything gets inserted perfectly. What am I doing wrong here?
UPDATE: Is it correct to write the statement like this?
INSERT INTO Marketing
SELECT (@ProductID, @MarketingTypeID, @MarketingTitle, @MarketingData)
WHERE NOT EXISTS
(SELECT * FROM Marketing)
Your
IF NOT EXISTS(SELECT * FROM Picklist)will skip the insert if any rows at all exist inPicklist.From your description of what happens when you change the position of the
ENDit seems there are rows in the table.I assume in fact you are trying to do an
UPSERT. What version of SQL Server are you on? If 2008 look intoMERGE