如何将逗号分隔的 NVARCHAR 转换为 SQL Server 2005 中的表记录? [英] How to convert comma separated NVARCHAR to table records in SQL Server 2005?
问题描述
我有一个以逗号分隔的 ID 列表,例如:
I have a list of ids separated by comma like:
1,17,25,44,46,67,88
我想把它们转换成一个表记录(变成一个临时表)
I want to convert them to a table records ( into a temporary table ) like
#tempTable
number_
--------
1
17
25
44
46
67
88
可以使用函数,一个表值函数吗?
It is possible with a function, a table-valued one ?
我为什么要这个?我想将 INNER JOIN
子句(进入存储过程)与另一个表一起使用,例如:
Why I want this ? I want to use for INNER JOIN
clause (into stored procedure) with another table(s) like as:
SELECT a,b,c FROM T1
INNER JOIN functionNameWhichReturnsTable
ON functionNameWhichReturnsTable.number_ = T1.a
我不能使用 IN
因为我将使用接受 NVARCHAR 类型参数的存储过程.该参数将提供 ID 列表.
I cannot use IN
because I will use stored procedure which accepts a parameter of type NVARCHAR. That parameter will provide the list of ids.
谢谢
推荐答案
可能与 分隔逗号分隔值并存储在 sql server 的表中.
请尝试使用 逗号分隔值中的精确值到表:
CREATE FUNCTION [dbo].[ufn_CSVToTable] ( @StringInput VARCHAR(8000), @Delimiter nvarchar(1))
RETURNS @OutputTable TABLE ( [String] VARCHAR(10) )
AS
BEGIN
DECLARE @String VARCHAR(10)
WHILE LEN(@StringInput) > 0
BEGIN
SET @String = LEFT(@StringInput,
ISNULL(NULLIF(CHARINDEX(@Delimiter, @StringInput) - 1, -1),
LEN(@StringInput)))
SET @StringInput = SUBSTRING(@StringInput,
ISNULL(NULLIF(CHARINDEX(@Delimiter, @StringInput), 0),
LEN(@StringInput)) + 1, LEN(@StringInput))
INSERT INTO @OutputTable ( [String] )
VALUES ( @String )
END
RETURN
END
GO
使用 XML 以其他方式检查需求:
Check the requirement in other way using XML:
DECLARE @param NVARCHAR(MAX)
SET @param = '1:0,2:1,3:1,4:0'
SELECT
Split.a.value('.', 'VARCHAR(100)') AS CVS
FROM
(
SELECT CAST ('<M>' + REPLACE(@param, ',', '</M><M>') + '</M>' AS XML) AS CVS
) AS A CROSS APPLY CVS.nodes ('/M') AS Split(a)
这篇关于如何将逗号分隔的 NVARCHAR 转换为 SQL Server 2005 中的表记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!