September 1, 2010 at 8:13 am
Declare @sss varchar(100)
Set @sss ='12,11,23,34,567,690,4,1'
or
--- Set @sss ='45,56,89,212,121,33,14,7,101,4,22'
or
--- Set @sss ='334,234,217,1,4,333'
How to select last value after comma?
( For example result from first string =1 , second =22 , third =333)
September 1, 2010 at 8:25 am
You can use the REVERSE() Function, to help start from the end, and the charIndex, to find the comma. I added a case to ensure a comma is added at the end, for scenarios where there were none.
SELECT REVERSE(SUBSTRING(REVERSE(@sss), 0,
CHARINDEX(',', REVERSE(@sss) + ',', 0)))
Cheers,
J-F
September 1, 2010 at 11:52 am
We can use left function also.
Declare @sss varchar(100)
Set @sss ='12,11,23,34,567,690,4,321'
set @sss = reverse(@sss)
set @sss = reverse(left(@sss,charindex(',',@sss) - 1))
print @sss
September 1, 2010 at 2:11 pm
Depending on how many of these you have to do, this may work better:
select top (1) Item
from dbo.DelimitedSplit8K(@sss, ',')
order by ItemNumber desc;
Click here for the latest Delimited Split Function.
Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes
September 1, 2010 at 9:00 pm
Just a suggestion... Doing 2 or 3 REVERSE's tends to be a bit expensive even compared to an ISNULL/NULLIF combo. If you're guaranteed to always have a comma, then you can remove the ISNULL/NULLIF combo from the following and still only need one REVERSE.
DECLARE @sss TABLE (StringNumber INT, String VARCHAR(100))
INSERT INTO @sss
(StringNumber, String)
SELECT 1, '12,11,23,34,567,690,4,1' UNION ALL
SELECT 2, '45,56,89,212,121,33,14,7,101,4,22' UNION ALL
SELECT 3, '334,234,217,1,4,333' UNION ALL
SELECT 4, '1234' UNION ALL
SELECT 5, '' UNION ALL
SELECT 6, ','
SELECT StringNumber,
String,
RIGHT(String,ISNULL(NULLIF(CHARINDEX(',',REVERSE(String))-1,-1),LEN(String)))
FROM @sss
--Jeff Moden
Change is inevitable... Change for the better is not.
September 3, 2010 at 12:49 pm
change in the string - additional comma after last number.
I need last value from string.
Declare @sss varchar(100)
Set @sss ='12,11,23,34,567,690,4,1,'
or
--- Set @sss ='45,56,89,212,121,33,14,7,101,4,22,'
or
--- Set @sss ='334,234,217,1,4,333,'
September 3, 2010 at 12:57 pm
You should be able to figure this out... Charindex has an optional parameter, look it up in BOL.
Cheers,
J-F
September 3, 2010 at 1:34 pm
J-F Bergeron (9/3/2010)
You should be able to figure this out... Charindex has an optional parameter, look it up in BOL.
Spot on.
--Jeff Moden
Change is inevitable... Change for the better is not.
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply