从SQL server表中的varchar列获取子字符串

时间:2013-07-12 09:10:39

标签: sql sql-server sql-server-2005

我有一个名为Name的列,在列中我有值

Name
001 BASI Distributor (EXAM)
002 BASI Supplier (EXAM2)
MASI DISTRIBUTOR (EXAM002)
MASI SUPPLIER (EXAM003)
EXAM_ND Distributor Success System Test (EXAM_ND)
EXAM_SS Supplier Success System Test (EXAM_SS)

现在我想把()里面的值与整个字符串分开。我怎么会得到这个我试过SUBSTRING (Name ,22 ,4 )但是这对于我希望得到结果的单个问题有帮助一些独特的解决方案。

4 个答案:

答案 0 :(得分:5)

SELECT  SUBSTRING(Name,
        CHARINDEX('(', Name) + 1,
        CHARINDEX(')', Name) - CHARINDEX('(', Name) - 1)

答案 1 :(得分:3)

还有一个选择:

SELECT *, REPLACE(SUBSTRING(Name, CHARINDEX('(', Name) + 1, LEN(Name)), ')', '')
FROM dbo.test136

这假设您的CHARINDEX值在括号内的部分之后永远不会包含任何内容,从而避免了一次)调用(搜索结束Name)。如果他们这样做,请使用其他建议。

答案 2 :(得分:3)

试试这个 -

DECLARE @temp TABLE (st NVARCHAR(50))

INSERT INTO @temp (st)
VALUES 
     ('001 BASI Distributor (EXAM)'),
     ('002 BASI Supplier (EXAM2)'),
     ('MASI DISTRIBUTOR (EXAM002)'),
     ('MASI SUPPLIER (EXAM003)'),
     ('EXAM_ND Distributor Success System Test (EXAM_ND)'),
     ('EXAM_SS Supplier Success System Test (EXAM_SS)')

SELECT SUBSTRING(
     st, 
     CHARINDEX('(', st) + 1, 
     CHARINDEX(')', st) - CHARINDEX('(', st) - 1
)
FROM @temp

输出 -

-------------
EXAM
EXAM2
EXAM002
EXAM003
EXAM_ND
EXAM_SS

答案 3 :(得分:-1)

请尝试:

SELECT 
    REPLACE(SUBSTRING(Name, PATINDEX('%(%', Name)+1, LEN(Name)), ')', '')
FROM 
    YourTable