日期:2014-05-18  浏览次数:20557 次

高手帮忙改一下这个case when语句,不知道如何改,查了很多资料也没作对
gsid   in   (case   when   @companyname   is   null   or   @companyname=0   then   gsid   else  
--注释中间的部份是一老大写出来的,单独执行没有问题,出的结果是如212,11,254,2122之类的数组,可是放在这里执行会报错,报的是经典的将varchar转换为int时出错.
(select   gsid   from   duizhaobiao   as   tmp
where   exists
(
select   *   from   duizhaobiao   as   tmpA
where   exists
(
select   1   from   t_userlogin
where  
charindex(rtrim(tmpA.gsid),@companyname)> 0
)   and   zyid   =   tmp.zyid   ))
--
end   )


上面是我套出来的语句,gsid   为null   或是为0时执行正常,如果我按网上的方法改成:

gsid   in   (case   when   @companyname   is   null   or   @companyname=0   then   gsid   else  
--仔细看这一部分就更不对了,
CHARINDEX( ', '+CONVERT(NVARCHAR(20),gsid)+ ', ',   ', '+ '(select   gsid   from   duizhaobiao   as   tmp
where   exists
(
select   *   from   duizhaobiao   as   tmpA
where   exists
(
select   1   from   t_userlogin
where  
charindex(rtrim(tmpA.gsid),@companyname)> 0
)   and   zyid   =   tmp.zyid   ))+ ', ')> 0
------
end   )


高手帮改一下吧,顺便讲一下这种语句求出的结果要如何应用在in语句中


------解决方案--------------------
第一個語句,蠻奇怪的,比如t_userlogin這個table好像都沒用到:(

還是貼出表的結構和部份數據,想要的結果,看看能不能重新寫..
------解决方案--------------------
case when 中的条件的数据类型必须与then后面的数据类型一致
------解决方案--------------------
rtrim(gsid) in (case when @companyname is null or @companyname=0 then rtrim(gsid) else
(select gsid from duizhaobiao as tmp
where exists
(
select * from duizhaobiao as tmpA
where exists
(
select 1 from t_userlogin
where
charindex(rtrim(tmpA.gsid),@companyname)> 0
) and zyid = tmp.zyid ))
end )