首页 > 解决方案 > 同一列的 Where 子句中的多个条件

问题描述

如何为以下条件编写 MS SQL 语句?

我有一个表单,允许用户在范围内输入日期 ( fromDate& toDate) 和 ID ( fromID& toID)。所有字段都可以为空仅输入 from 或 to 字段输入 from 和 to 字段。选择基于输入的值进行选择。以下是在 where 子句中检查输入值的条件。

no value entered => skip all conditions

value entered in fromDate only => Date = frDate

value entered in toDate only => Date <= toDate

value entered in both fromDate & toDate => Date between fromDate and toDate

Condition is applied to ID field as well.

任何建议都将受到高度赞赏。提前致谢。

标签: sql-servertsql

解决方案


您可以使用动态查询来解决您的问题。你的问题并不完全清楚。在这里,我给你一个解决方案,这将帮助你解决你的问题。尝试这个:

1.在存储过程中创建动态查询

        CREATE PROCEDURE sp_YourSPName
    /* Input Parameters */
        @FromDate DATETIME ,
        @ToDate DATETIME 
    AS
        SET NOCOUNT ON
        /* Variable Declaration */
        DECLARE @SQLQuery AS NVARCHAR(4000)
        DECLARE @ParamDefinition AS NVARCHAR(2000) 

        /* Build the Transact-SQL String with the input parameters */ 
        SET @SQLQuery = 'Select * From YourTableName where (1=1) ' 

        /* check for the condition and build the WHERE clause accordingly */
        IF (@FromDate IS NOT NULL)
           AND (@ToDate IS NOT NULL)
            SET @SQLQuery = @SQLQuery + 
                ' And (YourDate BETWEEN @FromDate AND @ToDate)'

        IF (@FromDate IS NULL)
           AND (@ToDate IS NOT NULL)
            SET @SQLQuery = @SQLQuery + ' And (YourDate <= @ToDate)' 

        IF (@FromDate IS NOT NULL)
           AND (@ToDate IS NULL)
            SET @SQLQuery = @SQLQuery + ' And (YourDate = @FromDate)'


        /* Specify Parameter Format for all input parameters included 
        in the stmt */
        SET @ParamDefinition = '@StartDate DateTime,
                            @EndDate DateTime'
        /* Execute the Transact-SQL String with all parameter value's  Using sp_executesql Command */

        EXECUTE sp_Executesql @SQLQuery,
             @ParamDefinition,
             @FromDate,
             @ToDate

        IF @@ERROR <> 0
            GOTO ErrorHandler

        SET NOCOUNT OFF
        RETURN(0)

        ErrorHandler :
        RETURN(@@ERROR)
    GO

2.执行存储过程:

EXEC sp_YourSPName '01 Oct 2018', '01 Oct 2018'

有关更多信息,请参阅此链接


推荐阅读