Share via

Extract values from the string

Rishabh Patil 161 Reputation points
2022-09-14T10:56:37.813+00:00

Hi All,

I have one Input string parameter in the stored procedure of type nvarchar(max)

'10=1,11=0,12=1,13=0'
In the string 10=1 is nothing but Server ID = Status. So server 10 is enabled , server 11 is disabled etc

Now, I want to extract these values from this string for all 4 servers and insert into my table

ServerInfoDetails (ServerID, Status)

Could you please help me understand how can I extract values?

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

0 comments No comments

Answer accepted by question author

Yitzhak Khabinsky 27,196 Reputation points
2022-09-14T12:21:05.397+00:00

Hi @Rishabh Patil ,

Please try the following solution.

SQL

DECLARE @ServerInfoDetails TABLE (ServerID INT PRIMARY KEY, Status BIT);  
  
DECLARE @param nvarchar(max) = '10=1,11=0,12=1,13=0';  
  
INSERT INTO @ServerInfoDetails (ServerID, Status)  
SELECT ServerID = LEFT(value, pos - 1)  
 , Status = RIGHT(value, LEN(value) - pos)  
FROM STRING_SPLIT(@param, ',')  
 CROSS APPLY (SELECT CHARINDEX('=', value)) AS t(pos);  

-- test  
SELECT * FROM @ServerInfoDetails;  

Output

+----------+--------+  
| ServerID | Status |  
+----------+--------+  
|       10 |      1 |  
|       11 |      0 |  
|       12 |      1 |  
|       13 |      0 |  
+----------+--------+  

Was this answer helpful?

0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Jingyang Li 5,901 Reputation points Volunteer Moderator
    2022-09-14T15:28:52.68+00:00

    Use JSON with YitzhakKhabinsky-0887's sample:
    DECLARE @ServerInfoDetails TABLE (ServerID INT PRIMARY KEY, Status BIT);

     DECLARE @param nvarchar(max) = '10=1,11=0,12=1,13=0';  
      
     --select * from  openjson('{"'+Replace(Replace(@param, '=','":"'),',','","') +'"}')  
       
          
     INSERT INTO @ServerInfoDetails (ServerID, Status)   
      
     select [key],value   
     from  openjson('{"'+Replace(Replace(@param, '=','":"'),',','","') +'"}')  
       
     SELECT * FROM @ServerInfoDetails;  
      
    

    Was this answer helpful?

    1 person found this answer helpful.

Your answer

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