SQL server SPLIT String

Santhosh Kunder 41 Reputation points
2022-12-06T07:51:56.28+00:00

Can someone help me with a function to get a part of the text from this string?

L=CTV,OU=CALUBCO,OU=testext,DC=Test,DC=com  

I need the value OU=CALUBCO from the text above.

Thanks in advance!

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,492 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,707 questions
{count} votes

Accepted answer
  1. Yitzhak Khabinsky 26,576 Reputation points
    2022-12-06T13:51:03.21+00:00

    Hi @Santhosh Kunder ,

    Please try the following solution based on tokenization via JSON.
    It will work starting from SQL Server 2016 onwards.

    We are looking for the 2nd token in the comma separated list of tokens.
    JSON array starts from 0 (zero).

    SQL

    -- DDL and sample data population, start  
    DECLARE @tbl TABLE (tokens VARCHAR(1000));  
    INSERT INTO @tbl (tokens) VALUES   
     ('L=CTV,OU=CALUBCO,OU=testext,DC=Test,DC=com');  
    -- DDL and sample data population, end  
       
    SELECT Result = JSON_VALUE(S,'$[1]')  
    FROM @tbl  
    CROSS APPLY (VALUES ('["' + REPLACE(STRING_ESCAPE(tokens,'json'),',','","') + '"]')) AS B(S);  
    

    Output

    +------------+  
    |   Result   |  
    +------------+  
    | OU=CALUBCO |  
    +------------+  
    
    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Jingyang Li 5,896 Reputation points Volunteer Moderator
    2022-12-06T15:54:28.573+00:00
     /* string_split in SQL 2022  */  
     DECLARE @str varchar(200)='L=CTV,OU=CALUBCO,OU=testext,DC=Test,DC=com'   
        
     select * from  string_split(@str,',',1)  
     Where ordinal=2  
    
    2 people found this answer helpful.

  2. NikoXu-msft 1,916 Reputation points
    2022-12-06T08:01:05.997+00:00

    Hi @Santhosh Kunder ,

    select SUBSTRING('L=CTV,OU=CALUBCO,OU=ShellExternal,DC=shell,DC=com',CHARINDEX(',',' L=CTV,OU=CALUBCO,OU=ShellExternal,DC=shell,DC=com'),10)  
    

    Best regards,
    Niko

    ----------

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.