如何从格式化的字符串中获取子字符串

时间:2014-03-20 09:58:53

标签: sql sql-server tsql

我想从sql的给定字符串 Praveen(403162)中获取子字符串 403162

3 个答案:

答案 0 :(得分:3)

SELECT SUBSTRING(column_name, CHARINDEX('(', column_name)+1, CHARINDEX(')', column_name)-CHARINDEX('(', column_name)-1) from table_name

DEMO

答案 1 :(得分:1)

你可以这样做:

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

如果您想在一行中执行此操作:

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

答案 2 :(得分:0)

Declare @Name VARCHAR(100)

Select @Name = 'Praveen(403162)'

Select @Name = SUBSTRING(@name,PATINDEX('%[0-9]%',@Name),LEN(@Name))
Select SUBSTRING (@Name,1,6)