获取SQL Server中某些字符或特定字符后的字符串

时间:2015-03-30 04:21:40

标签: sql-server regex

我有一个字符串模式,如列“备注”:

remarks
pay mode: called to pay
pay mode: cash
pay mode: bank deposit
pay mode: from third party

我必须在pay mode:之后选择所有字符串。一种方法是在第一次出现:值后检索所有字符串,或者从左边的9个字符后选择左边的所有字符串。

如何在SQL Server中执行此操作?

5 个答案:

答案 0 :(得分:0)

一种方法是使用Substring + Charindex

SELECT Substring('pay mode: called to pay', Charindex(':', 'pay mode: called to pay')
                                                + 1, Len('pay mode: called to pay')) 

或使用Right + Charindex

SELECT RIGHT('pay mode: called to pay', Len('pay mode: called to pay') -
                                             Charindex(':', 'pay mode: called to pay')) 

答案 1 :(得分:0)

检查一下并希望它可以帮助你

Create table #table1
(
Remarks varchar(100)
)

Insert into #table1 values('pay mode: called to pay'),
('pay mode: cash'),
('pay mode: bank deposit'),
('pay mode: from third party')


Select substring(Remarks,11,len(Remarks)) from #table1

更好的方法是,您也可以使用CHARINDEX。检查此查询:

Select SUBSTRING(Remarks, CHARINDEX(':',Remarks)+1, len(Remarks)) from #table1

答案 2 :(得分:0)

我会使用case来确保字符串采用预期格式:

select (case when remarks like 'pay mode: %'
             then stuff(remarks, 1, 10, '')
             else remarks
        end)

或者,也许是一个更通用的解决方案:

select (case when remarks like '%: %'
             then stuff(remarks, 1, charindex(': ', remarks)+1, '')
             else remarks
        end)

编辑:

正如Firebird指出的那样,使用case时不需要stuff()。这使得这个解决方案对于冒号更加优雅。当没有匹配时,charindex()返回0,因此在这种情况下没有任何反应。你可以这样做:

select stuff(remarks, 1, charindex(':', remarks), '')

但是,要在之后捕获空间,需要使用case()ltrim()

答案 3 :(得分:0)

选择修剪(备注,'付费模式:','')备注 FROM TableName

答案 4 :(得分:0)

为了在字符串的基础上进行拆分,请将其用作SQL Server函数。将sql server函数定义为

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[split](
          @delimited NVARCHAR(MAX),
          @delimiter NVARCHAR(100)
        ) RETURNS @t TABLE (id INT IDENTITY(1,1), val NVARCHAR(MAX))
        AS
        BEGIN
          DECLARE @xml XML
          SET @xml = N'<t>' + REPLACE(@delimited,@delimiter,'</t><t>') + '</t>'

          INSERT INTO @t(val)
          SELECT  r.value('.','varchar(MAX)') as item
          FROM  @xml.nodes('/t') as records(r)
          RETURN
END

您可以将此功能称为dbo.split('pay mode: called to pay', 'pay mode:')