这是我的表
create table Table1 (Id int, ...some fields... , CategoryId int, ProfileId int)
我想编写一个SP(存储过程),它将根据传递给SP的参数从表中提供搜索结果。这是我的程序
Create proc Search
(
@MediaType1 varchar(1000),
@MediaType2 varchar(1000),
@MediaType3 varchar(1000)
)
as
begin
select * from table
where
case when @MediaType1 = '' then 1 else CategoryId end in
(select case when @MediaType1 = '' then 1 else Splvalue end
from dbo.Split(case @MediaType1 when '0,' then '1,2,3,4' when '' then '1,' else @MediaType1 end,','))
and
case when @MediaType2 = '' then 1 else ProfileId end in
(select case when @MediaType2 = '' then 1 else Splvalue end
from dbo.Split(case @MediaType2 when '0,' then '2,12,13' when '' then '1,' else @MediaType2 end,','))
and
case when @MediaType3 = '' then 1 else ProfileId end in
(select case when @MediaType3 = '' then 1 else Splvalue end
from dbo.Split(case @MediaType3 when '0,' then '1,14,15,16' when '' then '1,' else @MediaType3 end,','))
end
基本上,我想要达到的目标是' 0' 0在@ MediaType1变量中传递,它应该返回所有具有类别(1,2,3,4)的记录,否则它应该只传递那个传递的类别(例如3)否则如果它的空白,它应该显示所有记录。 @ MediaType2和@ MediaType3的方式相同,只是它们应该检查ProfileId。条件也是所有三个或两个或一个参数可能是空白的,我需要处理它们并显示过滤后的记录。
我的上述查询仅在传递一个参数且其余全部为空时才有效。我也试过
where
(@MediaType1 <> '' and Category in (select Splvalue from dbo.Split(@MediaType1,',')))
or
(@MediaType2 <> '' and ProfileId in (select Splvalue from dbo.Split(@MediaType2 ,',')))
or
(@MediaType3 <> '' and ProfileId in (select Splvalue from dbo.Split(@MediaType3 ,',')))
但即使这样也行不通。任何帮助将不胜感激
答案 0 :(得分:0)
如果我只是重写你所说的条件:
SELECT * FROM table
WHERE
(@MediaType1 = '' OR (@MediaType1 = 0 AND CategoryId IN (1,2,3,4))
OR @MediaType1 = CategoryId)
AND
(@MediaType2 = '' OR (@MediaType2 = 0 AND ProfileId IN (1,2,3,4))
OR @MediaType2 = ProfileId )
AND
(@MediaType3 = '' OR (@MediaType3 = 0 AND ProfileId IN (1,2,3,4))
OR @MediaType3 = ProfileId )
答案 1 :(得分:0)
我刚刚写了这样的SP,它起作用了
Create proc Search
(
@MediaType1 varchar(1000),
@MediaType2 varchar(1000),
@MediaType3 varchar(1000)
)
as
begin
if (@MediaType1 = '' and @MediaType2 = '' and @MediaType3 = '')
begin
set @MediaType1 = '0,';
set @MediaType2 = '0,';
set @MediaType3 = '0,';
end
select * from table
where
((@MediaType1 = '0,' and CategoryId in (1,2,3,4)) or (CategoryId in (select Splvalue from dbo.Split(@MediaType1,','))))
or
((@MediaType2 = '0,' and ProfileId in (2,12,13)) or (ProfileId in (select Splvalue from dbo.Split(@MediaType2 ,','))))
or
((@MediaType3 = '0,' and ProfileId in (1,14,15,16)) or (ProfileId in (select Splvalue from dbo.Split(@MediaType3 ,','))))
end