Search code examples
sqlsql-serverstored-procedureswhere-clausedynamic-sql

Building dynamic where condition in SQL statement


I want to build custom Where condition based on stored procedure inputs, if not null then I will use them in the statement, else I will not use them.

if @Vendor_Name is not null
    begin 

    set @where += 'Upper(vendors.VENDOR_NAME) LIKE "%"+ UPPER(@Vendor_Name) +"%"'

    end
    else if @Entity is not null
    begin
    set @where += 'AND headers.ORG_ID = @Entity'
    end
select * from table_name where @where

But I get this error

An expression of non-boolean type specified in a context where a condition is expected, near 'set'.

Solution

  • Use this :

    Declare @Where NVARCHAR(MAX) 
    
    ...... Create your Where
    
    DECLARE @Command NVARCHAR(MAX) 
    Set @Command = 'Select * From SEM.tblMeasureCatalog AS MC ' ;
    
    If( @Where <> '' )
       Set @Comand = @Command + ' Where ' + @Where
    
    Execute SP_ExecuteSQL  @Command
    

    I tested this and it Worked