Conditional Where子句:除了动态查询之外还有什么方法可以写?

时间:2012-09-04 13:18:03

标签: sql sql-server sql-server-2008

这是我的查询,不编译:

Select 1 from dbo.EmailAddresses e
    Inner Join Users u On e.UserID = u.UserID
        Where LOWER(EmailAddress) = @EmailAddress               
        And
    Case When @For = 1 Then e.JurisdictionID IS NOT NULL  When @For = 2 Then e.AccountID IS NOT NULL  End

有人能告诉我一种在没有动态查询的情况下编写此查询的方法,即在字符串中构建查询吗?

2 个答案:

答案 0 :(得分:2)

这应该有效:

Select 1 from dbo.EmailAddresses e
    Inner Join Users u On e.UserID = u.UserID
        Where LOWER(EmailAddress) = @EmailAddress               
        And (
            (@For = 1 AND e.JurisdictionID IS NOT NULL) OR
            (@For = 2 AND e.AccountID IS NOT NULL)
        )

答案 1 :(得分:2)

尝试 简单而且有一种方法可以在没有案例的情况下尝试..

Select 1 from dbo.EmailAddresses e 

    Inner Join Users u On e.UserID = u.UserID 
        Where LOWER(EmailAddress) = @EmailAddress                        
And  (   (@For = 1 and e.JurisdictionID IS NOT NULL)
        or ( @For = 2 and e.AccountID IS NOT NULL  ))