我使用以下查询:
if(@usertype = 'all')
begin
select *
from tbllogin a
left join tblUserType_Master b on a.typeid = b.id
where (b.user_type = 'agent' or b.user_type = 'branch') ;
end
else if(@usertype = 'branch')
begin
select *
from tbllogin a
left join tblUserType_Master b on a.typeid = b.id
where b.user_type = 'branch' ;
end
else if(@usertype = 'agent')
begin
select *
from tbllogin a
left join tblUserType_Master b on a.typeid = b.id
where b.user_type = 'agent' ;
end
这完全正常,但三个查询之间的唯一区别是where条件。有没有办法可以将where条件的值存储在变量中,只需将其添加到公共部分即可。
答案 0 :(得分:1)
Use CASE Statement in WHERE Clause to get your result :
SELECT * FROM tbllogin a
LEFT OUTER JOIN tblUserType_Master b ON a.typeid=b.id
WHERE ( @usertype='all' AND b.user_type IN ('agent','branch') ) OR
b.user_type = CASE WHEN @usertype='branch' THEN 'branch'
WHEN @usertype='agent' THEN 'agent' END
答案 1 :(得分:1)
就我所见,你已经拥有了一个具有该值的变量。为什么不简单地使用它:
select
*
from
tbllogin a
left join tblUserType_Master b on a.typeid=b.id
where
b.user_type = @usertype or (@usertype='all' and b.usertype in ('branch','agent'))
我还想指出一些事情:你使用左连接但是与右边的表比较,这将消除 tbllogin 无论如何, tblUserType_Master 中没有匹配。
您可以执行以下操作,它肯定会表现得更好:
select
*
from
tbllogin a
inner join tblUserType_Master b on a.typeid=b.id
where
b.user_type = @usertype or (@usertype='all' and b.usertype in ('branch','agent'))
另外,我强烈建议不要使用select *,明确列出列是推荐路径。