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.
In previous articles i explained How to Separate integer and fractional part from decimal number and Insert multiple records in table in single insert statement and Concatenate rows values as a comma separated string using for xml path and stuff in sql server and Count number of occurrences of character or word in a string in sql
and Pass table name as parameter to sql server stored procedure or query and Remove first or last character from string or column 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:
- CHARINDEX is used to find the position of the comma in the string.
- Based on the CHARINDEX of the comma the Left function pulls everything left of the indicated position
- 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.
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..