问题描述
我正在一个页面上显示记录,我需要一种方法让用户选择要在另一个页面上显示的那些记录的子集.这些记录不会存储在动态生成的任何地方.
I am displaying records on a page, and I need a way for the user to select a subset of those records to be displayed on another page. These records aren't stored anywhere the are a dynamically generated thing.
在 sql 中,最好的方法是说一个 uniqueid 在这个 ids 列表中的哪个位置而不是在表等中.我知道我可以用一堆 ors 动态构建 sql,但这似乎是一个黑客.其他人有什么建议吗?
What is the best way to in sql to say where a uniqueid is in this list of ids not in a table etc. I know I could dynamically construct the sql with a bunch of ors, but that seems like a hack. anyone else have any suggestions?
推荐答案
这是最好的来源:
http://www.sommarskog.se/arrays-in-sql.html
创建一个拆分函数,并像这样使用它:
create a split function, and use it like:
SELECT
*
FROM YourTable y
INNER JOIN dbo.splitFunction(@Parameter) s ON y.ID=s.Value
要使此方法起作用,您需要进行一次时间表设置:
For this method to work, you need to do this one time table setup:
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
INTO Numbers
FROM sys.objects s1
CROSS JOIN sys.objects s2
ALTER TABLE Numbers ADD CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number)
设置 Numbers 表后,创建此函数:
Once the Numbers table is set up, create this function:
CREATE FUNCTION [dbo].[FN_ListToTable]
(
@SplitOn char(1) --REQUIRED, the character to split the @List string on
,@List varchar(8000)--REQUIRED, the list to split apart
)
RETURNS TABLE
AS
RETURN
(
----------------
--SINGLE QUERY-- --this will not return empty rows
----------------
SELECT
ListValue
FROM (SELECT
LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(@SplitOn, List2, number+1)-number - 1))) AS ListValue
FROM (
SELECT @SplitOn + @List + @SplitOn AS List2
) AS dt
INNER JOIN Numbers n ON n.Number < LEN(dt.List2)
WHERE SUBSTRING(List2, number, 1) = @SplitOn
) dt2
WHERE ListValue IS NOT NULL AND ListValue!=''
);
GO
您现在可以轻松地将 CSV 字符串拆分为一个表格并在其上加入:
You can now easily split a CSV string into a table and join on it:
select * from dbo.FN_ListToTable(',','1,2,3,,,4,5,6777,,,')
输出:
ListValue
-----------------------
1
2
3
4
5
6777
(6 row(s) affected)
您可以将 CSV 字符串传递到过程中并仅处理给定 ID 的行:
Your can pass in a CSV string into a procedure and process only rows for the given IDs:
SELECT
y.*
FROM YourTable y
INNER JOIN dbo.FN_ListToTable(',',@GivenCSV) s ON y.ID=s.ListValue
这篇关于将一列与 t-sql 中的值列表进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!