I'm trying to have an IF block after an INSERT INTO statement and depending on some conditions, execute a different SELECT that will feed the INSERT INTO.
Here's a (failing) example of what I'm trying to do:
INSERT INTO #TempTable (COL1, COL2, COL3)
IF @VAR = 'YES'
BEGIN
SELECT * FROM TABLE
END
ELSE
BEGIN
SELECT * FROM TABLE WHERE REGDATE <= '2015-06-12'
END
But I always end up with this when trying to save the stored proc.
Incorrect syntax near the keyword 'IF'
I thought of building a string and using sp_executesql
but I think my initial approach would be less prone to error.
Another option would be to use a
CASE
statement orIF
statement. Maybe this? It is pretty close to what you had: