如何在sql的条件下使用大小写?

时间:2011-02-09 21:17:17

标签: sql-server-2005 tsql

以下是存储过程的一部分: -

@ID int
@Col1 int
@Col2 int

Select * 
from Table_01 t1
JOIN table_02 t2 on t1.col = t2.col
where 
  1 = case when @Col1 = 0 then 1 else (case when t2.Col1 = @Col1 then 1 else 0 end) end
  AND 1 = case when @Col2 = 0 then 1 else (case when t2.Col2 = @Col2 then 1 else 0 end) end
  AND 1 = case when @ID = 0 then 1 else (case when t2.ID = @ID then 1 else 0 end) end

目前

  • 如果@ID = 0则忽略条件
  • 如果@ID有值,则它会根据条件满意度
  • 返回结果

我需要在那里添加另一个条件: -

if @ID = -1然后不应该返回任何结果(因为没有匹配) 但它应该像@ID = 0(忽略添加表达)

我清楚了吗? :(

3 个答案:

答案 0 :(得分:0)

Select ...
From Table_01 As t1
    Join table_02 As t2 
        On t1.col = t2.col
Where Case 
        When @ID = 0 Then 1 
        When t2.ID = @ID Then 1 
        When @ID = -1 Then 0
        Else 0 
        End = 1

如果最后一个条件胜过其他两个条件,则需要更改顺序:

Select ...
From Table_01 As t1
    Join table_02 As t2 
        On t1.col = t2.col
Where Case 
        When @ID = -1 Then 0
        When @ID = 0 Then 1 
        When @ID = t2.ID Then 1 
        Else 0 
        End = 1

当然,另一种可能表现更好的方式(假设@ID = -1胜过):

Select ...
From Table_01 As t1
    Join table_02 As t2 
        On t1.col = t2.col
Where @ID != -1 
    And ( @ID = 0 Or @ID = t2.ID )

根据OP的修改进行更新

听起来你正在尝试做类似以下的事情:

Select ...
From Table_01 As t1
    Join table_02 As t2 
        On t1.col = t2.col
Where @ID != -1
    And ( @Col1 = 0 Or @Col1 = t2.Col1 )
    And ( @Col2 = 0 Or @Col2 = t2.Col2 )
    And ( @ID = 0 Or @ID = t2.ID )

答案 1 :(得分:0)

我会尝试写它以便更清楚:

WHERE @ID IN (0, t2.ID) AND @ID <> -1

WHERE (@ID = 0 OR t2.ID = @ID) AND @ID <> -1

如果t2.ID不能为-1,则表示您不需要该部分。

答案 2 :(得分:0)

如果我理解正确,您只需要@ID = -1@ID = 0具有相同的效果。在这种情况下,您的查询可能如下所示:

Select * 
FROM Table_01 t1
  JOIN table_02 t2 on t1.col = t2.col
WHERE @Col1 IN (0, t2.Col1)
  AND @Col2 IN (0, t2.Col2)
  AND @ID IN (-1, 0, t2.ID)