如何在 T-SQL 中使用逗号分隔的值列表作为过滤器?

How do I use a comma separated list of values as a filter in T-SQL?(如何在 T-SQL 中使用逗号分隔的值列表作为过滤器?)
本文介绍了如何在 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

干杯

这篇关于如何在 T-SQL 中使用逗号分隔的值列表作为过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)