如何编写查询以满足搜索条件

时间:2011-12-02 11:08:21

标签: sql-server stored-procedures

我需要建议写一个满足这些条件的查询。

我将三个参数传递给存储过程:

  • to date
  • from date
  • is active

要求是这样的:

  • 页面加载显示谁是今天的regisatar
  • 仅传递to date然后我只需要显示那些注册到日期的人
  • 传递from date时仅显示那个日期之后的人
  • 并且只有那些落在他们之间的人

我尝试了但这完全是浪费。

If (@viewPending = 1 or @viewPending = 0 )
    Begin
        IF @TDate IS NULL AND @FDate IS NOT NULL
            SELECT 
            RegDate,
            CenterName  As [Center Name],
            OwnerName   As [Owner Name],
            MobileNo    As [Mobile],
            MailID      As [EMail ID],
            isVerified  As [Verified]
        FROM  TBL_iREGFORM
        WHERE REGDATE >= @FDate AND isVerified in (Case When  @viewPending =1 Then 0 Else 1 | 0 End) 
      IF @TDate IS NOT NULL AND @FDate IS  NULL
            SELECT 
            RegDate,
            CenterName  As [Center Name],
            OwnerName   As [Owner Name],
            MobileNo    As [Mobile],
            MailID      As [EMail ID],
            isVerified  As [Verified]
        FROM  TBL_iREGFORM
        WHERE REGDATE <= @FDate AND isVerified in (Case When  @viewPending =1 Then 0 Else 1 | 0 End)
       IF @TDate IS NOT NULL AND @FDate IS NOT NULL
            SELECT 
            RegDate,
            CenterName  As [Center Name],
            OwnerName   As [Owner Name],
            MobileNo    As [Mobile],
            MailID      As [EMail ID],
            isVerified  As [Verified]
        FROM  TBL_iREGFORM
        WHERE REGDATE BETWEEN  @FDate AND @TDATE AND isVerified in (Case When  @viewPending =1 Then 0 Else 1 | 0 End)
    ELSE

            SELECT 
            RegDate,
            CenterName  As [Center Name],
            OwnerName   As [Owner Name],
            MobileNo    As [Mobile],
            MailID      As [EMail ID],
            isVerified  As [Verified]
        FROM  TBL_iREGFORM
        WHERE REGDATE =CONVERT(VARCHAR(10),GETDATE(),103) AND isVerified in (Case When  @viewPending =1 Then 0 Else 1 | 0 End)

1 个答案:

答案 0 :(得分:4)

SELECT * FROM
  MyTable
WHERE
  ( @startDate IS NULL OR RegisterDate >= @startDate )
AND ( @endDate IS NULL OR RegisterDate <= @endDate )
AND ( @active IS NULL OR Active = @active )