Question

How do I write a query in SQL where when the string variable is not '' we include the WHERE clause and check where the ID exists in the list or not?
The following does not seem to work.

DECLARE @var varchar(20)
DECLARE @clause varchar(20)
DECLARE @sql varchar(20)

SET @var= '1,2,3'
IF @var <> ''
SET @clause=' WHERE ID IN ('+ @var + ')'

SET @sql='SELECT  [ID]
  ,[SOURCE]
  ,[LAST_KEY]
FROM [oms].[dbo].[MIGRATION]' 

EXEC (@sql + @clause)

Error Message: Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword 'WHERE'.

Was it helpful?

Solution

Increase your @sql variable's length to MAX like

DECLARE @sql varchar(MAX)

You have defined 20 length which is not enough to store whole query in that variable. Also remove @clause variable and change your code like below. You can also print whole query by print @sql and check what is wrong in that.

DECLARE @var varchar(500)
DECLARE @sql varchar(MAX)

SET @var= '1,2,3'

SET @sql = 'SELECT  [ID], 
                    [SOURCE], 
                    [LAST_KEY] 
            FROM    [oms].[dbo].[MIGRATION]' 

IF @var IS NOT NULL AND @var <> ''
BEGIN
    SET @sql = @sql + ' WHERE ID IN ('+ @var + ')'
END

EXEC (@sql)

OTHER TIPS

This issue is because of length for variable @sql. Please change it from @sql varchar(20) to @sql varchar(max) will resolve your issue.

Below is the code for the same

  DECLARE @var varchar(20)
DECLARE @clause varchar(20)
DECLARE @sql varchar(max)

SET @var= '1,2,3'
IF @var <> ''
SET @clause=' WHERE ID IN ('+ @var + ')'

SET @sql='SELECT  [ID]
  ,[SOURCE]
  ,[LAST_KEY]
FROM [oms].[dbo].[MIGRATION]' 

EXEC (@sql + @clause)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top