I have a table 이렇게
Value String
-------------------
1 Cleo, Smith
I want to 분리하십시오 쉼표로 구분된 문자열이어야 열 두 조각으로
Value Name Surname
-------------------
1 Cleo Smith
열 두 개만 데릭쉐퍼드와 고정식입니다 추가
귀하의 목적에 사용하여 해결할 수 있습니다 다음 qeury -
Select Value , Substring(FullName, 1,Charindex(',', FullName)-1) as Name,
Substring(FullName, Charindex(',', FullName)+1, LEN(FullName)) as Surname
from Table1
그래서 우리는 함수를 만들 필요가 없는 기성품 분할되었습니다 sql server 의 사용자 정의 함수.
CREATE FUNCTION Split (
@InputString VARCHAR(8000),
@Delimiter VARCHAR(50)
)
RETURNS @Items TABLE (
Item VARCHAR(8000)
)
AS
BEGIN
IF @Delimiter = ' '
BEGIN
SET @Delimiter = ','
SET @InputString = REPLACE(@InputString, ' ', @Delimiter)
END
IF (@Delimiter IS NULL OR @Delimiter = '')
SET @Delimiter = ','
--INSERT INTO @Items VALUES (@Delimiter) -- Diagnostic
--INSERT INTO @Items VALUES (@InputString) -- Diagnostic
DECLARE @Item VARCHAR(8000)
DECLARE @ItemList VARCHAR(8000)
DECLARE @DelimIndex INT
SET @ItemList = @InputString
SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)
WHILE (@DelimIndex != 0)
BEGIN
SET @Item = SUBSTRING(@ItemList, 0, @DelimIndex)
INSERT INTO @Items VALUES (@Item)
-- Set @ItemList = @ItemList minus one less item
SET @ItemList = SUBSTRING(@ItemList, @DelimIndex+1, LEN(@ItemList)-@DelimIndex)
SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)
END -- End WHILE
IF @Item IS NOT NULL -- At least one delimiter was encountered in @InputString
BEGIN
SET @Item = @ItemList
INSERT INTO @Items VALUES (@Item)
END
-- No delimiters were encountered in @InputString, so just return @InputString
ELSE INSERT INTO @Items VALUES (@InputString)
RETURN
END -- End Function
GO
---- Set Permissions
--GRANT SELECT ON Split TO UserRole1
--GRANT SELECT ON Split TO UserRole2
--GO
;WITH Split_Names (Value,Name, xmlname)
AS
(
SELECT Value,
Name,
CONVERT(XML,'<Names><name>'
+ REPLACE(Name,',', '</name><name>') + '</name></Names>') AS xmlname
FROM tblnames
)
SELECT Value,
xmlname.value('/Names[1]/name[1]','varchar(100)') AS Name,
xmlname.value('/Names[1]/name[2]','varchar(100)') AS Surname
FROM Split_Names
또한 확인란 대한 아래 링크를 참조
http://jahaines.blogspot.in/2009/06/converting-delimited-string-of-values.html
xml 기반 대답은 간단하고 명료하게
이) 는 다음과 같은 뜻이 있다
DECLARE @S varchar(max),
@Split char(1),
@X xml
SELECT @S = 'ab,cd,ef,gh,ij',
@Split = ','
SELECT @X = CONVERT(xml,' <root> <myvalue>' +
REPLACE(@S,@Split,'</myvalue> <myvalue>') + '</myvalue> </root> ')
SELECT T.c.value('.','varchar(20)'), --retrieve ALL values at once
T.c.value('(/root/myvalue)[1]','VARCHAR(20)') , --retrieve index 1 only, which is the 'ab'
T.c.value('(/root/myvalue)[2]','VARCHAR(20)'),
T.c.value('(/root/myvalue)[3]','VARCHAR(20)')
FROM @X.nodes('/root/myvalue') T(c)
금지커서 적용하십시오 함께
select ParsedData.*
from MyTable mt
cross apply ( select str = mt.String + ',,' ) f1
cross apply ( select p1 = charindex( ',', str ) ) ap1
cross apply ( select p2 = charindex( ',', str, p1 + 1 ) ) ap2
cross apply ( select Nmame = substring( str, 1, p1-1 )
, Surname = substring( str, p1+1, p2-p1-1 )
) ParsedData
이 시도하시겠습니까 (& # 39 의 인스턴스들도 변경하십시오. & # 39. & # 39, & # 39 를;; 무엇이든 간에 사용하려는 구분)
CREATE FUNCTION dbo.Wordparser
(
@multiwordstring VARCHAR(255),
@wordnumber NUMERIC
)
returns VARCHAR(255)
AS
BEGIN
DECLARE @remainingstring VARCHAR(255)
SET @remainingstring=@multiwordstring
DECLARE @numberofwords NUMERIC
SET @numberofwords=(LEN(@remainingstring) - LEN(REPLACE(@remainingstring, ' ', '')) + 1)
DECLARE @word VARCHAR(50)
DECLARE @parsedwords TABLE
(
line NUMERIC IDENTITY(1, 1),
word VARCHAR(255)
)
WHILE @numberofwords > 1
BEGIN
SET @word=LEFT(@remainingstring, CHARINDEX(' ', @remainingstring) - 1)
INSERT INTO @parsedwords(word)
SELECT @word
SET @remainingstring= REPLACE(@remainingstring, Concat(@word, ' '), '')
SET @numberofwords=(LEN(@remainingstring) - LEN(REPLACE(@remainingstring, ' ', '')) + 1)
IF @numberofwords = 1
BREAK
ELSE
CONTINUE
END
IF @numberofwords = 1
SELECT @word = @remainingstring
INSERT INTO @parsedwords(word)
SELECT @word
RETURN
(SELECT word
FROM @parsedwords
WHERE line = @wordnumber)
END
사용 예시:
SELECT dbo.Wordparser(COLUMN, 1),
dbo.Wordparser(COLUMN, 2),
dbo.Wordparser(COLUMN, 3)
FROM TABLE
지금까지 제안된 이미 많은 다른 방법으로 이 문제를 해결할 수 있으며 여러 가지 방법이 있습니다. 간단한 약간만이라도 왼쪽 '/' '및 기타 구체화하십시오 기능을 사용할 수 있는' 하위 원하는 결과를 얻기 위해.
DECLARE @tbl1 TABLE (Value INT,String VARCHAR(MAX))
INSERT INTO @tbl1 VALUES(1,'Cleo, Smith');
INSERT INTO @tbl1 VALUES(2,'John, Mathew');
SELECT
Value,
LEFT(String,CHARINDEX(',',String)-1) as Fname,
LTRIM(RIGHT(String,LEN(String) - CHARINDEX(',',String) )) AS Lname
FROM @tbl1
이 외곽진입 실패할 경우 2 가지 항목을 더 구체화하십시오. 이러한 상황에서 후 피봇 '또는' 를 사용하여 이용할 수 있다 '' 를 사용하여 XML '와' 오노스 변환하십시오 문자열이어야 afaq 구체화하십시오 할 수 있습니다. 그동안 'XML 기반 솔루션을 통해 그들의 솔루션이므로 아드 브르 및 세부 아웃해야'
이 질문에 대한 답은 ',' 를 사용하는 동안 사용할 수 있는 모든 비효율적임 분할. 이것 [성능 비교] (http://sqlperformance.com/2012/07/t-sql-queries/split-strings). 가장 좋은 '는' DelimitedSplit8K splitters 를 중심으로 만들어진 제프 모덴. [Here] 이에 대한 자세한 내용을 확인할 수 있습니다 (http://www.sqlservercentral.com/articles/Tally+Table/72993/)
DECLARE @tbl1 TABLE (Value INT,String VARCHAR(MAX))
INSERT INTO @tbl1 VALUES(1,'Cleo, Smith');
INSERT INTO @tbl1 VALUES(2,'John, Mathew');
SELECT t3.Value,[1] as Fname,[2] as Lname
FROM @tbl1 as t1
CROSS APPLY [dbo].[DelimitedSplit8K](String,',') as t2
PIVOT(MAX(Item) FOR ItemNumber IN ([1],[2])) as t3
Value Fname Lname
1 Cleo Smith
2 John Mathew
CREATE FUNCTION [dbo].[DelimitedSplit8K]
/**********************************************************************************************************************
Purpose:
Split a given string at a given delimiter and return a list of the split elements (items).
Notes:
1. Leading a trailing delimiters are treated as if an empty string element were present.
2. Consecutive delimiters are treated as if an empty string element were present between them.
3. Except when spaces are used as a delimiter, all spaces present in each element are preserved.
Returns:
iTVF containing the following:
ItemNumber = Element position of Item as a BIGINT (not converted to INT to eliminate a CAST)
Item = Element value as a VARCHAR(8000)
Statistics on this function may be found at the following URL:
http://www.sqlservercentral.com/Forums/Topic1101315-203-4.aspx
CROSS APPLY Usage Examples and Tests:
--=====================================================================================================================
-- TEST 1:
-- This tests for various possible conditions in a string using a comma as the delimiter. The expected results are
-- laid out in the comments
--=====================================================================================================================
--===== Conditionally drop the test tables to make reruns easier for testing.
-- (this is NOT a part of the solution)
IF OBJECT_ID('tempdb..#JBMTest') IS NOT NULL DROP TABLE #JBMTest
;
--===== Create and populate a test table on the fly (this is NOT a part of the solution).
-- In the following comments, "b" is a blank and "E" is an element in the left to right order.
-- Double Quotes are used to encapsulate the output of "Item" so that you can see that all blanks
-- are preserved no matter where they may appear.
SELECT *
INTO #JBMTest
FROM ( --# & type of Return Row(s)
SELECT 0, NULL UNION ALL --1 NULL
SELECT 1, SPACE(0) UNION ALL --1 b (Empty String)
SELECT 2, SPACE(1) UNION ALL --1 b (1 space)
SELECT 3, SPACE(5) UNION ALL --1 b (5 spaces)
SELECT 4, ',' UNION ALL --2 b b (both are empty strings)
SELECT 5, '55555' UNION ALL --1 E
SELECT 6, ',55555' UNION ALL --2 b E
SELECT 7, ',55555,' UNION ALL --3 b E b
SELECT 8, '55555,' UNION ALL --2 b B
SELECT 9, '55555,1' UNION ALL --2 E E
SELECT 10, '1,55555' UNION ALL --2 E E
SELECT 11, '55555,4444,333,22,1' UNION ALL --5 E E E E E
SELECT 12, '55555,4444,,333,22,1' UNION ALL --6 E E b E E E
SELECT 13, ',55555,4444,,333,22,1,' UNION ALL --8 b E E b E E E b
SELECT 14, ',55555,4444,,,333,22,1,' UNION ALL --9 b E E b b E E E b
SELECT 15, ' 4444,55555 ' UNION ALL --2 E (w/Leading Space) E (w/Trailing Space)
SELECT 16, 'This,is,a,test.' --E E E E
) d (SomeID, SomeValue)
;
--===== Split the CSV column for the whole table using CROSS APPLY (this is the solution)
SELECT test.SomeID, test.SomeValue, split.ItemNumber, Item = QUOTENAME(split.Item,'"')
FROM #JBMTest test
CROSS APPLY dbo.DelimitedSplit8K(test.SomeValue,',') split
;
--=====================================================================================================================
-- TEST 2:
-- This tests for various "alpha" splits and COLLATION using all ASCII characters from 0 to 255 as a delimiter against
-- a given string. Note that not all of the delimiters will be visible and some will show up as tiny squares because
-- they are "control" characters. More specifically, this test will show you what happens to various non-accented
-- letters for your given collation depending on the delimiter you chose.
--=====================================================================================================================
WITH
cteBuildAllCharacters (String,Delimiter) AS
(
SELECT TOP 256
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
CHAR(ROW_NUMBER() OVER (ORDER BY (SELECT NULL))-1)
FROM master.sys.all_columns
)
SELECT ASCII_Value = ASCII(c.Delimiter), c.Delimiter, split.ItemNumber, Item = QUOTENAME(split.Item,'"')
FROM cteBuildAllCharacters c
CROSS APPLY dbo.DelimitedSplit8K(c.String,c.Delimiter) split
ORDER BY ASCII_Value, split.ItemNumber
;
-----------------------------------------------------------------------------------------------------------------------
Other Notes:
1. Optimized for VARCHAR(8000) or less. No testing or error reporting for truncation at 8000 characters is done.
2. Optimized for single character delimiter. Multi-character delimiters should be resolvedexternally from this
function.
3. Optimized for use with CROSS APPLY.
4. Does not "trim" elements just in case leading or trailing blanks are intended.
5. If you don't know how a Tally table can be used to replace loops, please see the following...
http://www.sqlservercentral.com/articles/T-SQL/62867/
6. Changing this function to use NVARCHAR(MAX) will cause it to run twice as slow. It's just the nature of
VARCHAR(MAX) whether it fits in-row or not.
7. Multi-machine testing for the method of using UNPIVOT instead of 10 SELECT/UNION ALLs shows that the UNPIVOT method
is quite machine dependent and can slow things down quite a bit.
-----------------------------------------------------------------------------------------------------------------------
Credits:
This code is the product of many people's efforts including but not limited to the following:
cteTally concept originally by Iztek Ben Gan and "decimalized" by Lynn Pettis (and others) for a bit of extra speed
and finally redacted by Jeff Moden for a different slant on readability and compactness. Hat's off to Paul White for
his simple explanations of CROSS APPLY and for his detailed testing efforts. Last but not least, thanks to
Ron "BitBucket" McCullough and Wayne Sheffield for their extreme performance testing across multiple machines and
versions of SQL Server. The latest improvement brought an additional 15-20% improvement over Rev 05. Special thanks
to "Nadrek" and "peter-757102" (aka Peter de Heer) for bringing such improvements to light. Nadrek's original
improvement brought about a 10% performance gain and Peter followed that up with the content of Rev 07.
I also thank whoever wrote the first article I ever saw on "numbers tables" which is located at the following URL
and to Adam Machanic for leading me to it many years ago.
http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-numbers-table.html
-----------------------------------------------------------------------------------------------------------------------
Revision History:
Rev 00 - 20 Jan 2010 - Concept for inline cteTally: Lynn Pettis and others.
Redaction/Implementation: Jeff Moden
- Base 10 redaction and reduction for CTE. (Total rewrite)
Rev 01 - 13 Mar 2010 - Jeff Moden
- Removed one additional concatenation and one subtraction from the SUBSTRING in the SELECT List for that tiny
bit of extra speed.
Rev 02 - 14 Apr 2010 - Jeff Moden
- No code changes. Added CROSS APPLY usage example to the header, some additional credits, and extra
documentation.
Rev 03 - 18 Apr 2010 - Jeff Moden
- No code changes. Added notes 7, 8, and 9 about certain "optimizations" that don't actually work for this
type of function.
Rev 04 - 29 Jun 2010 - Jeff Moden
- Added WITH SCHEMABINDING thanks to a note by Paul White. This prevents an unnecessary "Table Spool" when the
function is used in an UPDATE statement even though the function makes no external references.
Rev 05 - 02 Apr 2011 - Jeff Moden
- Rewritten for extreme performance improvement especially for larger strings approaching the 8K boundary and
for strings that have wider elements. The redaction of this code involved removing ALL concatenation of
delimiters, optimization of the maximum "N" value by using TOP instead of including it in the WHERE clause,
and the reduction of all previous calculations (thanks to the switch to a "zero based" cteTally) to just one
instance of one add and one instance of a subtract. The length calculation for the final element (not
followed by a delimiter) in the string to be split has been greatly simplified by using the ISNULL/NULLIF
combination to determine when the CHARINDEX returned a 0 which indicates there are no more delimiters to be
had or to start with. Depending on the width of the elements, this code is between 4 and 8 times faster on a
single CPU box than the original code especially near the 8K boundary.
- Modified comments to include more sanity checks on the usage example, etc.
- Removed "other" notes 8 and 9 as they were no longer applicable.
Rev 06 - 12 Apr 2011 - Jeff Moden
- Based on a suggestion by Ron "Bitbucket" McCullough, additional test rows were added to the sample code and
the code was changed to encapsulate the output in pipes so that spaces and empty strings could be perceived
in the output. The first "Notes" section was added. Finally, an extra test was added to the comments above.
Rev 07 - 06 May 2011 - Peter de Heer, a further 15-20% performance enhancement has been discovered and incorporated
into this code which also eliminated the need for a "zero" position in the cteTally table.
**********************************************************************************************************************/
--===== Define I/O parameters
(@pString VARCHAR(8000), @pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
-- enough to cover NVARCHAR(4000)
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
;
GO
예를 들어, 이 함수를 사용하여 설명된 대로 깔끔한 페르세나미 생쥐라. (영문: http://www.sqlshack.com/parsing-and-rotating-delimited-data-in-sql-server-2012/
이 기능을 사용할 수 있도록 논리적으로 페르세나미 구문 분석 네 부분으로 개체 이름. 훌륭한 장점은 페르세나미 국한된 것이 아니라는 것 모든 함수 또는 문자열 구문 분석 그냥 SQL Server 개체 이름 - 네 부분으로 구분된 데이터가 점.
첫 번째 파라메트가 객체에는 분석할 수 있으며, 두 번째) 은 객체의 값을 블렌드합니다 반환되기를. 이 회사는 데이터 분석 및 회전 구분 협의하고 있지만 이름 / 휴대폰 번호를 사용할 수 있습니다 -) 는 데이터를 분석할 수 있다.
예:
USE COMPANY;
SELECT PARSENAME('Whatever.you.want.parsed',3) AS 'ReturnValue';
이 기사는 또한 일반적인 표 (스테) "라는 레프리스카르스 '를 사용하는 방법에 대해 설명합니다 표현식에서는 페르세나미 실행하십시오 아니했으니 재장착하여 구분 값. 다시 한 결과 집합을 임시 보거나 스테 유용하게 사용할 수 있다.
그 뒤 일부 열을 salesforce. 행뿐만 런피보트 기능에 변환할지 사용되어 왔다. 이 기능을 사용해 왔던 클린업하기 하리네스 substring 및 데이터 불일치 및 지연 함수 (새로운 SQL Server 2012년), 이전 기록을 참조할 수 있기 때문에 결국 사용되어 왔다.
이를 위해 string_split SQL Server 2016년 과 함께 사용할 수 있습니다.
create table commasep (
id int identity(1,1)
,string nvarchar(100) )
insert into commasep (string) values ('John, Adam'), ('test1,test2,test3')
select id, [value] as String from commasep
cross apply string_split(string,',')
이 기능을 하도록 만들 수 있습니다.
CREATE Function [dbo].[fn_CSVToTable]
(
@CSVList Varchar(max)
)
RETURNS @Table TABLE (ColumnData VARCHAR(100))
AS
BEGIN
IF RIGHT(@CSVList, 1) <> ','
SELECT @CSVList = @CSVList + ','
DECLARE @Pos BIGINT,
@OldPos BIGINT
SELECT @Pos = 1,
@OldPos = 1
WHILE @Pos < LEN(@CSVList)
BEGIN
SELECT @Pos = CHARINDEX(',', @CSVList, @OldPos)
INSERT INTO @Table
SELECT LTRIM(RTRIM(SUBSTRING(@CSVList, @OldPos, @Pos - @OldPos))) Col001
SELECT @OldPos = @Pos + 1
END
RETURN
END
그런 다음 우리 CSV 를 사용하여 각 열의 값을 구분 SELECT 문의
"' [Fn_split_string_to_column] (생성 함수 [dbo]. @string 노바르처 (최고), @delimiter 챨 (1) ) @Out_put 되돌려줍니다 표 ( [column_id] INT id (1, 1) NOT NULL, [value] 노바르처 (최대) ) TPC. 시작한다. @Value 너희가운데 노바르처 (최고), @pos INT = 0, @len INT = 0
설정되었습니다 @string = 케이스 오른쪽 (@string, 1) = @delimiter 때! 그럼 @string + @delimiter 다른 @string END
동시에 > 하리네스 (@delimiter, @string, @pos + 1). 0 시작한다. 설정되었습니다 @pos @len = 하리네스 (@delimiter, @string, @pos + 1) - 설정되었습니다 @value = SUBSTRING (@string, @pos, @len)
삽입하십시오 @out_put ([값을]) [열] 우트림 (트림 (@value)) 를 선택합니다.
@Pos 설정되었습니다 하리네스 (@delimiter, @string, @pos + @len) + 1 = END
반품하십시오. END
내 생각엔 같은 기능을 사용할 수 있습니다.
CREATE FUNCTION [dbo].[fn_split](
@str VARCHAR(MAX),
@delimiter CHAR(1)
)
RETURNS @returnTable TABLE (idx INT PRIMARY KEY IDENTITY, item VARCHAR(8000))
AS
BEGIN
DECLARE @pos INT
SELECT @str = @str + @delimiter
WHILE LEN(@str) > 0
BEGIN
SELECT @pos = CHARINDEX(@delimiter,@str)
IF @pos = 1
INSERT @returnTable (item)
VALUES (NULL)
ELSE
INSERT @returnTable (item)
VALUES (SUBSTRING(@str, 1, @pos-1))
SELECT @str = SUBSTRING(@str, @pos+1, LEN(@str)-@pos)
END
RETURN
END
이 함수를 호출할 수 있습니다 (예:
select * from fn_split('1,24,5',',')
Declare @test TABLE (
ID VARCHAR(200),
Data VARCHAR(200)
)
insert into @test
(ID, Data)
Values
('1','Cleo,Smith')
insert into @test
(ID, Data)
Values
('2','Paul,Grim')
select ID,
(select item from fn_split(Data,',') where idx in (1)) as Name ,
(select item from fn_split(Data,',') where idx in (2)) as Surname
from @test
페르세나미 () 함수를 사용하여
with cte as(
select 'Aria,Karimi' as FullName
Union
select 'Joe,Karimi' as FullName
Union
select 'Bab,Karimi' as FullName
)
SELECT PARSENAME(REPLACE(FullName,',','.'),2) as Name,
PARSENAME(REPLACE(FullName,',','.'),1) as Family
FROM cte
그 결과
Name Family
----- ------
Aria Karimi
Bab Karimi
Joe Karimi
이거 드세요.
declare @csv varchar(100) ='aaa,bb,csda,daass';
set @csv = @csv+',';
with cte as
(
select SUBSTRING(@csv,1,charindex(',',@csv,1)-1) as val, SUBSTRING(@csv,charindex(',',@csv,1)+1,len(@csv)) as rem
UNION ALL
select SUBSTRING(a.rem,1,charindex(',',a.rem,1)-1)as val, SUBSTRING(a.rem,charindex(',',a.rem,1)+1,len(A.rem))
from cte a where LEN(a.rem)>=1
) select val from cte
기능을 사용할 수 있습니다 '붙박이' STRING_SPLIT 따라서만 호환성에서는 13.0cm 사용할 수 있는 수준. 데이터베이스가 SQL Server, 호환성 및 실행 수준은 낮은 130 여 개의 'STRING_SPLIT' 기능을 찾을 수 없게 됩니다. 다음 명령을 사용하여 데이터베이스 호환성 수준을 변경할 수 있습니다.
ALTER DATABASE DatabaseName SET COMPATIBILITY_LEVEL = 130
문법
STRING_SPLIT ( string , separator )
린스트링 함수를 사용하여:)
select Value,
substring(String,1,instr(String," ") -1) Fname,
substring(String,instr(String,",") +1) Sname
from tablename;
두 가지 기능을 사용할
만약 우리가 이 길이 있는 문자열 인수를 되돌려줍니다 제공하지 않고 끝까지 구체화하십시오
저도 비슷한 문제가 발생할 수 있지만 이 문제에 관한 한 뒤 복잡한 스레드할 결심했다고 게시물로의 내 발견사항 내가 찾은 것은 이번이 처음이다. i know it 는 단순한 문제를 다른 사람들을 도울 수 있는 복잡한 해결책을 좋겠다 난 documentum. 스레드할 찾고 있지만 이 보다 복잡한 솔루션. 난 이미 문자열으로 분할하려면 redboot*용 5 번호 (열 이름: 각 숫자의 표시하십시오 레브레스피드) 과 별도의 열에. 예를 들면 다음과 같습니다. 8.1,2.2,2 /dev/raw/raw200 표시할 수 있다.
1 2 3 4 5
-------------
8 1 2 2 2
솔루션 1: xml 을 이용한 기능: 이 솔루션을 출시해 이들보 최저속 솔루션 제공
SELECT Distinct FeedbackID,
, S.a.value('(/H/r)[1]', 'INT') AS level1
, S.a.value('(/H/r)[2]', 'INT') AS level2
, S.a.value('(/H/r)[3]', 'INT') AS level3
, S.a.value('(/H/r)[4]', 'INT') AS level4
, S.a.value('(/H/r)[5]', 'INT') AS level5
FROM (
SELECT *,CAST (N'<H><r>' + REPLACE(levelsFeed, ',', '</r><r>') + '</r> </H>' AS XML) AS [vals]
FROM Feedbacks
) as d
CROSS APPLY d.[vals].nodes('/H/r') S(a)
해결 방법 2: 분할 함수를 사용하여, 피벗. (분할 함수 이름을 열 수 있는 데이터 문자열으로 분할합니다 행뿐만)
SELECT FeedbackID, [1],[2],[3],[4],[5]
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY feedbackID ORDER BY (SELECT null)) as rn
FROM (
SELECT FeedbackID, levelsFeed
FROM Feedbacks
) as a
CROSS APPLY dbo.Split(levelsFeed, ',')
) as SourceTable
PIVOT
(
MAX(data)
FOR rn IN ([1],[2],[3],[4],[5])
)as pivotTable
해결 방법 3. 문자열 조작 기능을 사용하여 중소기업 대상 솔루션을 통해 가장 빠른 차로 2 -
SELECT FeedbackID,
SUBSTRING(levelsFeed,0,CHARINDEX(',',levelsFeed)) AS level1,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),4) AS level2,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),3) AS level3,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),2) AS level4,
PARSENAME(REPLACE(SUBSTRING(levelsFeed,CHARINDEX(',',levelsFeed)+1,LEN(levelsFeed)),',','.'),1) AS level5
FROM Feedbacks
내가 사용하는 데 필요한 문자열 함수 값을 5 문자열이어야 레브레스피드 map_layer 이후 처음으로 구체화하십시오.
이 솔루션은 된 계기가 되길 바란다고 내 다른 방법을 찾고 스레드할 더 복잡한 분리-정합성 열
CREATE FUNCTION [dbo].[SplitString](
@delimited NVARCHAR(MAX),
@delimiter NVARCHAR(100)
) RETURNS @t TABLE ( val NVARCHAR(MAX))
AS
BEGIN
DECLARE @xml XML
SET @xml = N'<t>' + REPLACE(@delimited,@delimiter,'</t><t>') + '</t>'
INSERT INTO @t(val)
SELECT r.value('.','varchar(MAX)') as item
FROM @xml.nodes('/t') as records(r)
RETURN
END
이 기능은 가장 빠른:
CREATE FUNCTION dbo.F_ExtractSubString
(
@String VARCHAR(MAX),
@NroSubString INT,
@Separator VARCHAR(5)
)
RETURNS VARCHAR(MAX) AS
BEGIN
DECLARE @St INT = 0, @End INT = 0, @Ret VARCHAR(MAX)
SET @String = @String + @Separator
WHILE CHARINDEX(@Separator, @String, @End + 1) > 0 AND @NroSubString > 0
BEGIN
SET @St = @End + 1
SET @End = CHARINDEX(@Separator, @String, @End + 1)
SET @NroSubString = @NroSubString - 1
END
IF @NroSubString > 0
SET @Ret = ''
ELSE
SET @Ret = SUBSTRING(@String, @St, @End - @St)
RETURN @Ret
END
GO
사용 예시:
SELECT dbo.F_ExtractSubString(COLUMN, 1, ', '),
dbo.F_ExtractSubString(COLUMN, 2, ', '),
dbo.F_ExtractSubString(COLUMN, 3, ', ')
FROM TABLE