如何在 T-SQL 中使用逗号分隔的值列表作为过滤器?
我有一个基本的 SQL 查询,开头是:
I have a basic SQL query, starting with:
SELECT top 20 application_id, [name], location_id FROM apps
现在,我想完成它以便它做到这一点(用伪代码编写)
Now, I would like to finish it so that it does this (written in Pseudocode)
if @lid > 0 then
WHERE location_id IN (@lid)
else
WHERE location_id is all values in location_id column
<小时>
根据要求,这是一个例子
As requested, here is an example
application_id name location_id
----------------------------------------------------------
1 Joe Blogs 33
2 Sam Smith 234
3 Jeremy Carr 33
@locid 是用户给出的结果,例如'33, 234'
@locid is the results given by the user, for example '33, 234'
如果@lid 为空,那么我希望它输出带有名称和application_id 的location_id 的所有行.否则,我希望它输出与@lid 中提供的数字相关的所有行(代表 location_id.
If @lid is empty then I'd like it to output all rows for location_id with name and application_id. Otherwise, I'd like it to output all rows in relation to the provided numbers in @lid (standing for location_id.
所以,如果@lid 为 0:
So, if @lid is 0:
application_id name location_id
----------------------------------------------------------
1 Joe Blogs 33
2 Sam Smith 234
3 Jeremy Carr 33
否则,如果@lid 包含'33'
Otherwise, if @lid contains '33'
application_id name location_id
----------------------------------------------------------
1 Joe Blogs 33
3 Jeremy Carr 33
推荐答案
尝试使用 Case,它用于 IIF 或三元运算符.请检查此链接 http://msdn.microsoft.com/en-us/图书馆/ms181765.aspx
Try using Case, which serves the purpose of an IIF or a ternary operator. Please check this link http://msdn.microsoft.com/en-us/library/ms181765.aspx
干杯
相关文章