vendredi 12 juin 2015

Different SELECT's for an INSERT INTO

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'

Any other approach ? I thought of building a string and using sp_executesql but I think my initial approach would be less prone to error.

Thanks.

Aucun commentaire:

Enregistrer un commentaire