SQL使用IF的条件

时间:2016-02-17 05:19:57

标签: sql-server stored-procedures

我有像这样的表LEVEL

|name|level|type||
|a   | 1   | a1  |
|b   | 1   | a2  |
|c   | 2   | a1  |
|d   | 1   | a1  |
|e   | 3   | a3  |
|a   | 1   | a1  |
|a   | 1   | a1  |

我需要一个基于规则

的存储过程
if I send @name = a and @level = 1
- select all from table level where name = @name
if I send @name = b and @level = 2
- select all from table level where type = @type
if I send @name = b and @level = 3
- select all from table level where type = @type

我创建了这样的程序

SELECT * 
FROM LEVEL
WHERE
((@LEVEL IS NULL) OR 
(RIGHT(LEVEL,1) = RIGHT(@LEVEL,1) AND RIGHT(@LEVEL,1) = '1' AND NAME = @NAME) OR
(RIGHT(LEVEL,1) = RIGHT(@LEVEL,1) AND RIGHT(@LEVEL,1) = '2' AND TYPE = @TYPE) OR
(RIGHT(LEVEL,1) = RIGHT(@LEVEL,1) AND RIGHT(@LEVEL,1) = '3' AND TYPE = @TYPE))

但是当我发送@level = 1, @name = a, and @type = a1时,仍然会返回所有内容。

我认为我的WHERE子句是错的,但不知道在哪里以及为什么?

3 个答案:

答案 0 :(得分:0)

使用union all;

select *
from level
where name = @name and 
@level = 1 and @name = 'a'
--above select query return any result if  @name = a and @level = 1

union all

select *
from level
where type = @type and 
@name = 'b' and @level in (2, 3)
--above select query return any result 
--if @name = b and @level = 2 or @name = b and @level = 3

答案 1 :(得分:0)

Select * from level
Where 
(Name='a' and @level = 1)
Or
(Type=@type and @level=2 and @name='b')
Or
(Type=@type and @level=3 and @name='b')

答案 2 :(得分:0)

您可以查看此内容。条件数据不匹配,因此我更改了参数值。

Declare @table table (name varchar(5), level int, type varchar(5))

insert into @table values ('a', 1,'a1'),('b', 1,'a2'),('c', 2,'a1'),('d', 1,'a1'),('e', 3,'a3'),('a', 1,'a1'),('a', 1,'a1')

--uncomment for other parameter value
--declare @name varchar(5) = 'a', @level int = 1, @type varchar(5) = 'a1'
declare @name varchar(5) = 'b', @level int = 1, @type varchar(5) = 'a2' -- There is no rows, for @name = 'b' and @level (2, 3) and @type = 'a1'

select * from @table where  
(   name = @name and level = @level and 
    ( 
        (@name = 'a' and @level = 1 )
        or
    ( 
        (@name = 'b' and ( @level in (1, 2 ,3) )) and type = @type ) -- show only row 1 
    )
)

输出将来自第一个评论参数列表

name    level   type
a        1       a1
a        1       a1
a        1       a1

输出将来自第二个取消注释参数列表

name    level   type
b        1       a2