How to get a substring from a formatted string

前端 未结 3 1103
面向向阳花
面向向阳花 2021-01-29 09:57

I would like to get a substring 403162 from the given string Praveen(403162) in sql?

3条回答
  •  [愿得一人]
    2021-01-29 10:51

    You can do it like this:

    DECLARE @searchString NVARCHAR(20) = 'Praveen(403162)'
    DECLARE @startFrom INT= CHARINDEX('(',@searchstring) + 1
    DECLARE @length INT = CHARINDEX(')',@searchstring) - @startFrom
    SELECT SUBSTRING(@searchstring,@startFrom, @length) AS RESULT
    

    If you want to do this in one line:

    DECLARE @searchString NVARCHAR(20) = 'Praveen(403162)'
    SELECT SUBSTRING(@searchstring,
           CHARINDEX('(',@searchstring) + 1, 
           CHARINDEX(')',@searchstring) - CHARINDEX('(',@searchstring) - 1) AS RESULT
    

提交回复
热议问题