Please disable your adblock and script blockers to view this page
 

Sql Server Query to Split String from Comma and get Left and Right Part

Introduction: In this article I am going to share how to split a string by comma or anything and get left and right portion of the string in sql server.


Description: Suppose we have a string like “Hello,World” and we want to split this string by comma and get the left and right portion of the string.

Implementation: Let’s create an example to understand how to get this. 

DECLARE @str VARCHAR(50)='Hello,World';

SELECT LEFT(@str, CHARINDEX(',', @str)-1)as LeftPart, RIGHT(@str, LEN(@str)-CHARINDEX(',', @str)) as RightPart;

Result:
LeftPart
RightPart
Hello
World

Explanation:
  1. CHARINDEX is used to find the position of the comma in the string.
  2. Based on the CHARINDEX of the comma the Left function pulls everything left of the indicated position
  3. Right pulls everything to the right of the indicated position, which is the length of the string minus the position of the comma.
Another way to get the same result:

SELECT LEFT(@str,CHARINDEX(',',@str)-1) as LeftPart, RIGHT(@str,CHARINDEX(',',REVERSE(@str)) - 1) as RightPart

Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates.        
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily.. ConversionConversion EmoticonEmoticon