我在T-SQL中使用类似于此的表中的SELECT语句:
SELECT DISTINCT name, location_id, application_id FROM apps
WHERE ((application_id is null) or (application_id = '4'))
AND ((location_id is null) or (location_id = '3'))
Run Code Online (Sandbox Code Playgroud)
在搜索一个application_id或一个location_id时,这似乎工作正常,但如果我想为多个位置运行该语句,该怎么办?我想返回未知数量的location_id和application_id的所有结果.例如,如果我想在location_id的2,3,4,5中搜索某人,但只有一个application_id.我该怎么做?
先感谢您!
编辑:我是个白痴!我没有给你所有的全部细节,这让我听起来很容易.所有这些值都是从表格中给出的.用户必须从表中的列中选择id而不是插入它们.在对这个问题进行了一些研究后,我想出了一个似乎是一个可行解决方案的页面.
CREATE FUNCTION iter$simple_intlist_to_tbl (@list nvarchar(MAX))
RETURNS @tbl TABLE (number int NOT NULL) AS
BEGIN
DECLARE @pos int,
@nextpos int,
@valuelen int
SELECT @pos = 0, @nextpos = 1
WHILE @nextpos > 0
BEGIN
SELECT @nextpos = charindex(',', @list, @pos + 1)
SELECT @valuelen = CASE WHEN @nextpos > 0
THEN @nextpos
ELSE len(@list) + 1
END - @pos - 1
INSERT @tbl (number)
VALUES (convert(int, substring(@list, @pos + 1, @valuelen)))
SELECT @pos = @nextpos
END
RETURN
END
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮我完善它以满足我的需求吗?对不起,如果我的问题不是很清楚,因为我很难自己解决这个问题.
编辑2:在对主题进行更多阅读之后,似乎我需要一个存储过程来执行此操作.顶部的代码似乎是我需要的,但我无法根据自己的需要定制它.表结构如下:
application_id name location_id
------------------------------------------------------
1 Joe Blogs 34
2 John Smith 55
Run Code Online (Sandbox Code Playgroud)
根据我刚刚联系到的文章:
"处理这种情况的正确方法是使用一个将字符串解包到表中的函数.这是一个非常简单的函数:
因此,似乎我需要将这些值解压缩为字符串并使用此存储过程传递它们.关于如何让它工作的任何想法?
编辑3:我设法使用charindex()和convert()解决它,同时将它们设置在顶部.谢谢你的帮助,我再次为痛苦而道歉.