2016-05-31 56 views
0

我做这样的事情的正常工作:为什么SQL情况下条件给出错误

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'. 
+1

一个'CASE' *表达*必须返回SQL数据类型的标量值(每行)。它不能返回评估谓词的结果,因为这将是一个布尔值 - 而SQL Server没有布尔数据类型。 –

回答

1

使用andor条件,而不是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) 
) 
+0

抱歉不能理解呢..请解释ñ更多细节.. –

1

不能使用in子句case声明。因为Case必须为每个语句返回一个值(无论是true还是false)

要么您可以将查询分成两个块,要么可以使用“OR”子句。

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 

您还可以使用 “OR” 条款

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)) 

链接,关于类似问题的讨论低于

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/bc8a7a0b-1980-4481-a2df-6a5fde38f362/in-clause-in-case-statement?forum=sqlgetstarted

相关问题