TSQL - 如何从varchar字符串中提取数字

时间:2017-07-26 19:07:36

标签: tsql sql-server-2014

我正在使用Microsoft SQL Server 2014(SP2)。

我有一串以下格式的文字:

12/07/17 - Amount to pay £580.00 = Rent plus £55.58 per month - MC

值和内容会发生变化,但总是采用这种格式。

如何在单词pay之后提取数字值。在这种情况下它是'£580.00',但价值可能会有所不同,如'£20.00'或'£7.50'等。

由于

2 个答案:

答案 0 :(得分:2)

我喜欢John关于使用iTVF的想法,但是不需要承担基于计数器的分配器的费用。当你需要根据分隔符将一个字符串解析成很多行时,它们会非常棒,但是对于这样的事情总是过分杀人。

这是一个应该更快,更有效的替代方案......

CREATE FUNCTION dbo.tfn_ExtractPayAmount 
/* =========================================================================
Extracts the monetary amount following the 1st occurrence of the word "pay".
========================================================================= */
(
    @String VARCHAR(800)
)
RETURNS TABLE WITH SCHEMABINDING AS 
RETURN
    SELECT 
        RetValue = SUBSTRING(@String, sp.StartPosition, ISNULL(ep.EndPosition - sp.StartPosition, 0))
    FROM 
        ( VALUES (CHARINDEX(' pay ', @String, 1) + 5) ) sp (StartPosition)
        CROSS APPLY ( VALUES (IIF(sp.StartPosition = 5, NULL, CHARINDEX(' ', @String, sp.StartPosition + 1))) ) ep (EndPosition);
GO
HTH,Jason

答案 1 :(得分:1)

如果对TVF(表值功能)开放,请考虑以下

厌倦了提取字符串(left,right,charindex,patindex,...)我修改了一个解析函数来接受两个不相似的参数。在这种情况下'pay '' '

示例

Declare @YourTable table (ID int,SomeCol nvarchar(500))
Insert Into @YourTable values
(1,'12/07/17 - Amount to pay £580.00 = Rent plus £55.58 per month - MC')

Select A.*
      ,B.RetVal
 From  @YourTable A
 Cross Apply [dbo].[udf-Str-Extract](A.SomeCol,'pay ',' ') B
 Where try_convert(money,B.RetVal) is not null

<强>返回

enter image description here

感兴趣的UDF

CREATE FUNCTION [dbo].[udf-Str-Extract] (@String varchar(max),@Delimiter1 varchar(100),@Delimiter2 varchar(100))
Returns Table 
As
Return (  

with   cte1(N)   As (Select 1 From (Values(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) N(N)),
       cte2(N)   As (Select Top (IsNull(DataLength(@String),0)) Row_Number() over (Order By (Select NULL)) From (Select N=1 From cte1 N1,cte1 N2,cte1 N3,cte1 N4,cte1 N5,cte1 N6) A ),
       cte3(N)   As (Select 1 Union All Select t.N+DataLength(@Delimiter1) From cte2 t Where Substring(@String,t.N,DataLength(@Delimiter1)) = @Delimiter1),
       cte4(N,L) As (Select S.N,IsNull(NullIf(CharIndex(@Delimiter1,@String,s.N),0)-S.N,8000) From cte3 S)

Select RetSeq = Row_Number() over (Order By N)
      ,RetPos = N
      ,RetVal = left(RetVal,charindex(@Delimiter2,RetVal)-1) 
 From  (
        Select *,RetVal = Substring(@String, N, L) 
         From  cte4
       ) A
 Where charindex(@Delimiter2,RetVal)>1

)
/*
Max Length of String 1MM characters

Declare @String varchar(max) = 'Dear [[FirstName]] [[LastName]], ...'
Select * From [dbo].[udf-Str-Extract] (@String,'[[',']]')
*/
  

编辑 - 说明多个值的回归

Select A.*
      ,B.RetVal
 From  @YourTable A
 Cross Apply [dbo].[udf-Str-Extract](A.SomeCol,'£',' ') B
 Where try_convert(money,B.RetVal) is not null

<强>返回

enter image description here