我有一个在我的存储过程中传递给参数的连接值列表,我需要拆分这些值。
我的列表中可能有30个值,我已经展示了一些。我想将它们存储在temptable / table变量中。
CREATE PROCEDURE SAMPLE (@LIST VARCHAR(MAX),@USERNUM BIGINT,@COUNTRYNO BIGINT)
EXEC SAMPLE
'NAME:bankNO:branchNme:accountNbr:chequeddNbr:chequeddDte:payeeNme:branchCode'
,1,12001
期望的输出:
sno list val1 val2 val3 val4 val5 val6 val7
1 1:2:3:4:5:6:7 1 2 3 4 5 6 7
答案 0 :(得分:0)
您可以使用标准字符串拆分器,例如Jeff Moden的DelimitedSplit8K:http://www.sqlservercentral.com/articles/Tally+Table/72993/
CREATE FUNCTION [dbo].[DelimitedSplit8K]
--===== Define I/O parameters
(@pString VARCHAR(8000), @pDelimiter CHAR(1))
--WARNING!!! DO NOT USE MAX DATA-TYPES HERE! IT WILL KILL PERFORMANCE!
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 1 up to 10,000...
-- enough to cover VARCHAR(8000)
WITH E1(N) AS (
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
-- for both a performance gain and prevention of accidental "overruns"
SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
SELECT 1 UNION ALL
SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
SELECT s.N1,
ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
FROM cteStart s
)
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
Item = SUBSTRING(@pString, l.N1, l.L1)
FROM cteLen l
;
如果您需要将数据分成不同的列,请使用PIVOT:
SELECT 1 as sno, [1], [2], [3], [4], [5], [6], [7]
FROM (
SELECT
Item,
ItemNumber
from
dbo.DelimitedSplit8K ('A:B:C:1:2:3:4',':')
) AS S
PIVOT
(
max(Item) FOR ItemNumber IN ([1], [2], [3], [4], [5], [6], [7])
) AS PivotTable;
结果:
sno 1 2 3 4 5 6 7
1 A B C 1 2 3 4
答案 1 :(得分:0)
使用XML
拆分列表,使用PIVOT
将列表转换为列。
DECLARE @TempTable AS TABLE(Value VARCHAR(100), id int)
DECLARE @list AS VARCHAR(1000)
SET @list = 'NAME:bankNO:branchNme:accountNbr:chequeddNbr:chequeddDte:payeeNme:branchCode'
INSERT INTO @TempTable
SELECT
Split.a.value('.', 'VARCHAR(100)') AS CVS , ROW_NUMBER() OVER(ORDER BY Split.a.value('.', 'VARCHAR(100)'))
FROM
(
SELECT CAST ('<M>' + REPLACE(@list, ':', '</M><M>') + '</M>' AS XML) AS CVS
) AS A CROSS APPLY CVS.nodes ('/M') AS Split(a)
SELECT 1 as sno, @list AS List, * FROM @TempTable
pivot(MAX(Value) FOR id in([1],[2],[3],[4],[5],[6],[7],[8])) AS Piv