where子句中的case表达式

时间:2013-05-15 13:37:57

标签: sql-server tsql

如果testTable,我想从a = 4获取所有记录(6行)。 4是SP中的默认参数。

create table testTable(a int, b int, c int)
go
insert into testTable values(2, 101, 100000)
go
insert into testTable values(2, 101, 100001)
go
insert into testTable values(3, 101, 100002)
go
insert into testTable values(3, 102, 100003)
go
insert into testTable values(4, 1, 100004)
go
insert into testTable values(4, 1, 100005)
go

create proc SPtest
                @a int = 4,
                @b int = 1
as
select       * from testTable where a = @a and b = @b

exec SPtest 2, 101

以上效果很好。但是我需要这样的东西:

declare @a int
set @a = 4

select * 
from testTable 
where a = case @a when 4 then select distinct a from testTable end

2 个答案:

答案 0 :(得分:0)

切割cookie的方法很少,这似乎是最符合逻辑的;

IF @a = 4 THEN
BEGIN
  SELECT *
  FROM testTable
END
ELSE
BEGIN
  SELECT *
  FROM testTable
  WHERE a = @a and b = @b
END

或者你可以使用或声明;

SELECT *
FROM testTable 
WHERE @a = 4 or (a = @a and b = @b)

祝你好运(会评论但我还没有)。

此致

答案 1 :(得分:0)

请试试这个:

create proc SPtest
    @a int = 4,
    @b int = 1
as
if @a = 4
    select distinct a from testTable
else
    select * from testTable where a = @a and b = @b
go
exec SPtest
exec SPtest 3,101
相关问题