我做这样的事情很好:
select nameOfCols
from
FACost
inner join FAT as D on d.nid=a.atypeid
and
d.nid in (select item from SplitString('1,2,3,',','))
但是,当我使用案例来处理用户动态进入的情况时,可以进入''而不是' 1,2,3,'。然后它在我的案例条件中给出了错误
declare @selectedAssetTypeID varchar(50)='1,2,3,'
select nameOfCols
from
FACost
inner join FAT as D on d.nid=a.atypeid
and
case when @selectedAssetTypeID<>'' then d.nid in (select item from SplitString( @selectedAssetTypeID,',')) else d.nid=1 end //error causing lines
错误是:
Msg 156, Level 15, State 1, Line 33
Incorrect syntax near the keyword 'in'.
Msg 156, Level 15, State 1, Line 33
Incorrect syntax near the keyword 'else'.
答案 0 :(得分:1)
使用and
和or
条件而不是case
表达式。您拥有的case
表达式是指定值(else d.nid=1
)或检查真/假条件(d.nid in (select item from SplitString( @selectedAssetTypeID,','))
)。
and (
(@selectedAssetTypeID <>'' and d.nid in (select item from SplitString( @selectedAssetTypeID,',')) )
or (d.nid=1)
)
答案 1 :(得分:1)
您不能将in
子句与case
语句一起使用。因为Case
必须为每个语句返回一个值(true或false)
您可以将查询拆分为两个区块,也可以使用&#34; OR
&#34;子句。
IF @selectedAssetTypeID = " "
BEGIN
select nameOfCols
from FACost
inner join FAT as D
on (d.nid = a.atypeid)
where d.nid = 1
END
ELSE
BEGIN
select nameOfCols
from FACost
inner join FAT as D
on (d.nid = a.atypeid)
where d.nid IN
(select item from SplitString( @selectedAssetTypeID,','))
END
您还可以使用&#34; OR
&#34;条款
select nameOfCols
from FACost
inner join FAT as D
on (d.nid = a.atypeid)
where ((@selectedAssetTypeID <>'' and d.nid in (select item from SplitString(@selectedAssetTypeID,',')))
or (d.nid=1))
关于类似问题的讨论的链接如下