0

我想从testTableif中获取所有记录(6 行) a = 44是 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
4

2 回答 2

0

切饼干的方法很少,这似乎是最合乎逻辑的;

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

或者,您可以使用 or 语句;

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

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

问候,

于 2013-05-15T14:04:11.403 回答
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
于 2013-05-15T16:21:47.313 回答