Problem with CASE statement

  • Hi Everyone

    I have used CASE many times but not sure what I am doing wrong here.  SS won't accept it.  What am I doing wrong?  How can I fix it?

    SQL

    ALTER PROCEDURE [dbo].[WIP_UpdateEvents] (@FILENAME varchar(200), @RECORD_ADD_DATE datetime)
    AS

    DECLARE @FILEPATH VARCHAR(200)
    SET @FILEPATH = @FILENAME

    DECLARE @RECORD_ADD_DT varchar(26)
    SET @RECORD_ADD_DT = convert(varchar(26),@RECORD_ADD_DATE,121)

    DROP TABLE IF EXISTS #NEW

    DROP TABLE IF EXISTS #CURRENT

    CASE WHEN @FILEPATH LIKE '%Event_%'
    THEN
    Exec ( 'BULK INSERT #NEW
    FROM ''' +
    @FILEPATH +
    ''' WITH (FIRSTROW = 2, FIELDTERMINATOR = '','', ROWTERMINATOR = ''\n'', MAXERRORS = 0);'
    )
    END

    Error:

    Msg 156, Level 15, State 1, Procedure WIP_UpdateEvents, Line 47 [Batch Start Line 7]
    Incorrect syntax near the keyword 'CASE'.
    Msg 102, Level 15, State 1, Procedure WIP_UpdateEvents, Line 54 [Batch Start Line 7]
    Incorrect syntax near 'END'.

    Thank you

  • I re-wrote my code with an IF statement and that solved the issue.

  • As you discovered, case returns an expression. It does not execute an expression.

  • Lovely example for a bit of SQL injection

    Original author: https://github.com/SQL-FineBuild/Common/wiki/ 1-click install and best practice configuration of SQL Server 2019, 2017 2016, 2014, 2012, 2008 R2, 2008 and 2005.

    When I give food to the poor they call me a saint. When I ask why they are poor they call me a communist - Archbishop Hélder Câmara

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply