2017-08-31 111 views
1

非常簡單的問題,但似乎難以得到答案。通過select語句拆分字符串

如果我有這樣的:

declare @Agent nvarchar(4000) = '2131235,334225'; 

是否有一個select語句我可以寫分裂在昏迷是字符串,而無需編寫一個函數?

喜歡的東西:

SELECT SOME_SPLIT_LOGIC(@Agent) 

我想它返回:

Column 
-------- 
2131235 
334225 

請注意我用MS-SQL 2012

+0

SQL Server 2016中提供了一個內置函數(更多信息[here](https://docs.microsoft.com/en-us/sql/t- sql/functions/string-split-transact-sql)),但在Sql Server 2012中,我擔心你必須編寫自己的分割函數 – Andrea

+0

做一個Google搜索「Jeff Moden DelimitedSplit8K」。 –

回答

0
DECLARE @LeftPart TABLE 
(Agent int 
) 

DECLARE @RightPart TABLE 
(Agent1 int 
) 

declare @Agent nvarchar(4000) = '2131235,334225'; 

INSERT INTO @LeftPart 
SELECT LEFT(@Agent,7) 

INSERT INTO @RightPart 
SELECT RIGHT(@Agent,6) 

SELECT * INTO #Temp 
FROM 
(
SELECT * FROM @LeftPart 
UNION ALL 
SELECT * FROM @RightPart 
)A 

SELECT * FROM #Temp 
0

如何:

DECLARE @Agent VARCHAR(4000) = '2131235,334225' 
DECLARE @Delimiter VARCHAR(1) = ',' 

;WITH CTE 
AS 
(
    SELECT 1 AS ID 
    UNION ALL 
    SELECT ID + 1 FROM CTE 
    WHERE ID < 4000 
) 

SELECT 
    SUBSTRING(@Agent, t.ID, CHARINDEX(@Delimiter, @Agent + @Delimiter, t.ID) - t.ID) AS Agent 
FROM CTE t 
WHERE t.ID <= DATALENGTH(@Agent)+1 
    AND SUBSTRING(@Delimiter + @Agent, t.ID, 1) = @Delimiter 
OPTION (MAXRECURSION 4000) 

更多信息可以在這裏找到:http://www.sqlservercentral.com/articles/Tally+Table/72993/