Multiple conditional Where clause

后端 未结 2 2001
执笔经年
执笔经年 2021-01-15 18:45

I currently have a query that will pull a bunch of information from my database based on whatever where condition that I want to use.

declare @C         


        
2条回答
  •  终归单人心
    2021-01-15 19:20

    You might want to look into building your query.

    DECLARE @Number varchar(10)
    DECLARE @Where varchar(max)
    DECLARE @Query varchar(max)
    
    SET @Query = 'SELECT * FROM TestTable'
    SET @Where = ''
    
    SET @Number = '3'
    
    IF ISNULL(@Number, '') != ''
    BEGIN
        SET @Where = @Where + 'and testNumber = ' + @Number
    END
    
    IF LEN(@Where) > 0
    BEGIN
        SET @Where = SUBSTRING(@Where, 4, LEN(@Where))
    END
    
    if ISNULL(@Where, '') != ''
    BEGIN
        SET @Query = @Query + ' WHERE ' + @Where
    END
    
    EXEC(@Query)
    

    Check out this gentleman's article for reference: https://social.msdn.microsoft.com/forums/sqlserver/en-US/1ec6ffffd9-754b-4d78-8d3a-2b4da90e85dc/dynamically-building-where-clauses

提交回复
热议问题