sql查询与where子句中的日期比较

时间:2011-10-24 12:12:20

标签: sql

您好我有一个包含四列id,name,start_date,end_date。

的表

下面是我尝试从表中检索行的存储过程。

我将传递@status作为参数,该参数将具有值(1表示活动,2表示非活动,并且为null)

Alter procedure dbo.GetName(@id int, @statusDate VARCHAR(50))
begin 
select id, name  from customer 
where id = @id 
AND ((@statusDate  = 1 AND GETDATE() BETWEEN start_date AND end_date)
    OR (@statusDate = 2 AND GETDATE() BETWEEN start_date AND end_date) 
    OR @statusDate IS NULL)
end 

条件是

  • 如果@statusDate为1,则检索在开始日期和结束日期之间具有今天日期的行
  • 如果@statusDate为2,则检索在开始日期和结束日期之间没有今天日期的行
  • 如果@statusDate为null则检索所有行

请帮我修改和条件,以便根据上述条件检索行

3 个答案:

答案 0 :(得分:1)

那里有问题吗?

如果你的数据集很小(而且很小,取决于支持它的硬件),那么上面的查询似乎没问题(第二个条件中的逻辑错误除外;见下文)。如果您开始遇到性能问题,您可能希望使用条件块,如此(此语法适用于Microsoft SQL Server):

ALTER PROCEDURE dbo.GetName
    (
      @id INT
    , @statusDate BIT
    )
AS 
    BEGIN

        IF @StatusDate IS NULL 
            BEGIN
                SELECT  id
                      , name
                FROM    customer
                WHERE   id = @id
            END


        IF @statusDate = 1 
            BEGIN
                SELECT  id
                      , name
                FROM    customer
                WHERE   id = @id
                        AND GETDATE() BETWEEN start_date AND end_date

            END


        IF @statusDate = 2 
            BEGIN
                SELECT  id
                      , name
                FROM    customer
                WHERE   id = @id
                        AND ( GETDATE() < start_date
                              OR GETDATE() > end_date
                            )
            END

    END 

答案 1 :(得分:0)

尝试将null检查放在where子句的开头,如下所示:

select id, name  from customer 
where id = @id 
AND ((@statusDate IS NULL)
    OR (@statusDate  = 1 AND GETDATE() BETWEEN start_date AND end_date)
    OR (@statusDate = 2 AND NOT GETDATE() BETWEEN start_date AND end_date))

如果@statusDate为null,则您的子句始终为null,因此不会选择任何记录

答案 2 :(得分:0)

    SELECT id, name 
    FROM customer 
    WHERE id = @id 
      AND @statusDate  = 1 
      AND GETDATE() BETWEEN start_date AND end_date

UNION ALL

    SELECT id, name 
    FROM customer 
    WHERE id = @id 
      AND @statusDate  = 2 
      AND GETDATE() NOT BETWEEN start_date AND end_date

UNION ALL

    SELECT id, name 
    FROM customer 
    WHERE id = @id 
      AND @statusDate IS NULL