同一列的where子句中的多个条件

时间:2018-10-10 09:51:38

标签: sql-server tsql

如何为以下情况编写MS SQL语句?

我有一个表格,允许用户输入范围内的日期(fromDatetoDate)和ID(fromIDtoID)。对于所有 OR 输入所有字段,这些字段可以为空白。选择基于输入的值进行选择。以下是检查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.

任何建议都将受到高度赞赏。 预先感谢。

3 个答案:

答案 0 :(得分:0)

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

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'

For more info see this link

答案 1 :(得分:0)

下面是示例,而不是确切的查询,您可以尝试使用CASE语句将其放入您的方式

SELECT values     
FROM Table   
WHERE CASE 
     WHEN fromDate = null & todate = null THEN 
     WHEN fromDate != null & toDate != null THEN Date between fromDate and toDate
     WHEN fromDate != null THEN  Date = frDate
     WHEN toDate != null THEN Date = toDate

答案 2 :(得分:0)

您可以使用IS NULL来检查参数是否有价值

SELECT * FROM Table
    WHERE (@FromDate IS NULL OR Date > @FromDate) AND (@ToDate IS NULL OR Date < @ToDate)

同一查询类型将用于ID