SQL Server How to extract Certain nth character from a string in SQL

bqucvtff  于 4个月前  发布在  其他
关注(0)|答案(5)|浏览(30)

I have a field that returns the value as xxx-xxx-xxx-xxxxx-xx-x. How do i extract the 10th character from that code.

56lgkhnf

56lgkhnf1#

select substring('xxx-xxx-xxx-xxxxx-xx-x', 10, 1)

The documentation for the function on MSDN is here.

The SQL Fiddle demo is here (with different letters so you can clearly see which letter is extracted).

8dtrkrch

8dtrkrch2#

Use substring function

select substring('xxx-xxx-xax-xxxxx-xx-x', 10, 1)

pdsfdshx

pdsfdshx3#

you can use SUBSTRING , in your case use...

SELECT SUBSTRING(field, 10, 1)

field being the one that returns the value.

wpcxdonn

wpcxdonn4#

declare @x varchar(20) = 'xxx-xxx-xxx-xxxxx-xx-x'

select SUBSTRING(@x,10,CHARINDEX('-',@x)-4 )
ogsagwnx

ogsagwnx5#

the following code will return the nth substring after delimiting, either from left or from right; in the particular example the delimiter is comma, and it is looking for the 2nd segment, counting from right

declare

@str_orig VARCHAR(256)='123,345,8,6,7',
@delimit varchar(50) =',',
@loc int =2,
@from_left bit =0


SELECT value, row_number()  over( order by( select 1)) as row_num
into #split
FROM STRING_SPLIT(@str_orig, @delimit)

declare @result varchar(256)
if @from_left=1
 begin
 set @result = ( select top 1  value  from  #split  where row_num=@loc)
 end
else
 begin

 set @result = ( select top 1  value  from  #split
 where row_num= (SELECT MAX(ROw_num) -(@loc-1) FROM  #split)
 )
 
 end

select @result

相关问题