2013-05-15 81 views
0

如果a = 4想从testTable获得所有记录(6行)。 4是SP中的默认参数。案例表达式在where子句中

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 
+0

'CASE'在SQL Server只能返回 “原子” 的价值观 - 你不能运行'CASE'语句中的T-SQL代码。你需要从表中读取这些不同的值并将它们存储在一个变量**之前**执行此选择与案例在where子句 –

回答

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) 

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

问候,

+0

感谢您的尝试,但我需要的是: –

+0

按下意外进入。我需要如果@a = 3或@a = 2才能看到2行。如果@a = 4,我需要查看所有6条记录,而不用'IF'。这只是大查询的补充。 –

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 
+0

通过使用'IF'很容易解决。我不想在SP中有两次大的查询。我想用“CASE”表达来解决问题,就像我在原始问题中所说的那样。不管怎么说,还是要谢谢你。 –

+0

试试这个:select * from testTable where @a = 4 or(a = @a and b = @b) – PollusB