简体   繁体   中英

How to split the string value

Using SQL Server 2008

I want split the string by semicolon. string value come with semicolon sometimes without semicolon.

Example #1:

String = abceder-ere1212;eferere2121212 (with Semicolon)

Output

string1 = abceder-ere1212
string2 = eferere2121212

Example #2:

String: abcederdfdfd (without Semicolon)

Output

string1 = abcederdfdfd
string2 = ''

The below code is working, but I want to use in multiple places in the query , need a function instead of below code.

DECLARE
    @remarks varchar(max),
    @vc_pen varchar(max), 
    @vc_adjust varchar(max)

Select @remarks  = remarks    
from table1

SELECT   
   @vc_pen = SUBSTRING(S, 1, P - 1),
   @vc_adjust = SUBSTRING(S, P + 1, L - P)
FROM 
   (SELECT
        S = @remarks,
        P = CHARINDEX(';', @remarks),
        L = LEN(@remarks)) s;

How to write a query or function to split the string? Kindly assist

Try something generic like:

CREATE FUNCTION split
( 
    @string VARCHAR(MAX), 
    @delimiter CHAR(1) 
)  RETURNS @output TABLE(index INT, splitteddata VARCHAR(MAX)) 
BEGIN 
    DECLARE @start INT, @end INT, @index INT
    SELECT  @start = 1, @end = CHARINDEX(@delimiter, @string), @index = 1
    WHILE   @start < LEN(@string) + 1 BEGIN 
        IF  @end = 0  
            SET @end = LEN(@string) + 1

        INSERT INTO @output (splitteddata)  
        VALUES(@index, SUBSTRING(@string, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @index = @index + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)
    END 
   RETURN 
END

Query:
SELECT *
FROM split('abceder-ere1212;eferere2121212',';')
Output:
1 abceder-ere1212
2 eferere2121212

Try something like this....

Test Data

DECLARE @Table TABLE (ID INT, Value VARCHAR(MAX))

INSERT INTO @Table VALUES 
 (1 , 'abceder-ere1212;eferere2121212')
,(2 , 'abceder-ere1234')

Query

SELECT ID
       ,REPLACE(Split.a.value('.', 'VARCHAR(100)'), '000000', '') Value
       ,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) Output_Value
FROM   (SELECT ID
               ,Cast ('<M>' + Replace(CASE WHEN Value NOT LIKE '%;%' THEN  Value + ';000000'
                                     ELSE Value END
                      , ';', '</M><M>') + '</M>' AS XML) AS Data
        FROM   @Table) AS A
       CROSS APPLY Data.nodes ('/M') AS Split(a) 

Result

╔════╦═════════════════╦══════════════╗
║ ID ║      Value      ║ Output_Value ║
╠════╬═════════════════╬══════════════╣
║  1 ║ abceder-ere1212 ║            1 ║
║  1 ║ eferere2121212  ║            2 ║
║  2 ║ abceder-ere1234 ║            1 ║
║  2 ║                 ║            2 ║
╚════╩═════════════════╩══════════════╝

If there are only Two possible values

you can do the following

Test Data

DECLARE @Table TABLE (ID INT, Value VARCHAR(MAX))

INSERT INTO @Table VALUES 
 (1 , 'abceder-ere1212;eferere2121212')
,(2 , 'abceder-ere1234')

Query

;WITH CTE AS 
( SELECT  ID 
         ,REPLACE(CASE WHEN Value NOT LIKE '%;%' 
               THEN  Value + '|000000'
               ELSE Value END, ';', '|') AS Value
  FROM @Table
)
SELECT ID
      ,LEFT(Value , CHARINDEX('|', Value) -1) FirstValue
      ,REPLACE(RIGHT(Value,  LEN(Value) - CHARINDEX('|', Value)), '000000', '') SecondValue
FROM CTE

Result Set

╔════╦═════════════════╦════════════════╗
║ ID ║   FirstValue    ║  SecondValue   ║
╠════╬═════════════════╬════════════════╣
║  1 ║ abceder-ere1212 ║ eferere2121212 ║
║  2 ║ abceder-ere1234 ║                ║
╚════╩═════════════════╩════════════════╝

Try to use PARSENAME function like this:

SELECT PARSENAME(REPLACE(@remarks, ';', '.'), 2) AS string1,  
       PARSENAME(REPLACE(@remarks, ';', '.'), 1) AS string2  

Here is a code that will give your parts in separated fields:

DECLARE @text VARCHAR(1000);
SET @text = 'SELECT ''' + REPLACE(@remarks, ';', ''',''') + ''''
EXEC(@text)

In another way this is better (with sending result to a table):

DECLARE @text VARCHAR(1000)
SET @text = 'SELECT ''' + REPLACE(@remarks, ';', ''' As part union all SELECT ''') + ''' As part'
EXEC(@text)

And changing above to below for having a resultTable:

SET @text = 'SELECT part INTO resultTable FROM (select ''' + REPLACE(@remarks, ';', ''' As part UniON ALL SELECT ''') + ''' As part) dt '

I think this answer is useful when you set the results to a datatable or as result of a stored procedure .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM