如果SQL查询中的日期为空,则显示所有记录

时间:2013-10-31 11:46:33

标签: sql sql-server tsql

SET @dateFrom = ''
SET @dateTo = ''

SELECT [tNumber], [createdDate], [Total], [pfAmount] FROM [webtable]
WHERE [tNumber] LIKE '%' 
AND [createdDate] > @dateFrom+'%' 
AND [createdDate] < @dateTo+'%' 

如果日期为空,或者如果@dateFrom和@dateTo有值,那么我试图让查询显示数据库中的所有值,那么它应该过滤那些特定的结果

6 个答案:

答案 0 :(得分:1)

SELECT [tNumber], [createdDate], [Total], [pfAmount] FROM [webtable]
WHERE [tNumber] LIKE '%' 
AND (
        (       [createdDate] > @dateFrom --removed +'%'
            AND [createdDate] < @dateTo ) --close 2nd parentheses and removed +'%'
        OR      COALESCE(@dateFrom,@dateTo) IS NULL
    ) --close 1st parantheses

COALESCE()在括号内逐个评估一个东西,直到它找不到NULL值。如果所有值都为NULL,则返回NULL。通过我编写此语句的方式,如果两个参数都为NULL,则[createdDate]

不会过滤任何内容

更新

已移除+'%'

答案 1 :(得分:1)

尝试这个

    SET @dateFrom = ''
    SET @dateTo = ''

    SELECT [tNumber], [createdDate], [Total], [pfAmount] FROM [webtable]
    WHERE [tNumber] LIKE '%' 
    AND CASE 
            WHEN (@dateFrom = '' OR @dateTo = '') THEN ([createdDate] LIKE '%')
        ELSE  ([createdDate] BETWEEN @dateFrom and @dateTo)
        END

答案 2 :(得分:1)

试试这个:

SET @dateFrom = ''
SET @dateTo = ''
IF(@dateFrom = '' AND @dateTo='')
BEGIN
SELECT [tNumber], [createdDate], [Total], [pfAmount] FROM [webtable]
END
ELSE
BEGIN
SELECT [tNumber], [createdDate], [Total], [pfAmount] FROM [webtable]
WHERE [tNumber] LIKE '%' 
AND [createdDate] > convert(DATE,@dateFrom) 
AND [createdDate] < COnvert(Date,@dateTo)
END

答案 3 :(得分:0)

 declare @fdate datetime
 declare @tdate datetime
 set @fdate=''--'2013-10-10'
 set @tdate=''--'2013-10-10'
 select * from yourTable where (datefield>@fdate or @fdate='') and (datefield<@tdate or @tdate='') 

试试这个..

答案 4 :(得分:0)

SELECT [tNumber], [createdDate], [Total], [pfAmount] FROM [webtable]
WHERE [tNumber] LIKE '%' 
AND (@dateFrom = '' OR [createdDate] > @dateFrom+'%')
AND (@dateTo = '' OR [createdDate] < @dateTo+'%')

答案 5 :(得分:0)

要显示日期为空的记录为空,您可以使用以下查询

select * from [webtable] where ID not in (Select ID from [webtable] where  [createdDate] > COnvert(Date, ''))