Extracting dollar amounts from existing sql data?

亡梦爱人 提交于 2019-11-29 12:45:30
    CREATE FUNCTION dbo.fnGetAmounts(@str nvarchar(max))
    RETURNS TABLE 
    AS
    RETURN 
    (
    -- generate all possible starting positions ( 1 to len(@str))
    WITH StartingPositions AS
    (
        SELECT 1 AS Position
        UNION ALL
        SELECT Position+1
        FROM StartingPositions
        WHERE Position <= LEN(@str)
    )
   -- generate possible lengths
    , Lengths AS
    (
        SELECT 1 AS [Length]
        UNION ALL
        SELECT [Length]+1
        FROM Lengths
        WHERE [Length] <= 15
    )
    -- a Cartesian product between StartingPositions and Lengths
    -- if the substring is numeric then get it
    ,PossibleCombinations AS 
    (

         SELECT CASE                
                WHEN ISNUMERIC(substring(@str,sp.Position,l.Length)) = 1 
                   THEN substring(@str,sp.Position,l.Length)         
                 ELSE null END as Number
                 ,sp.Position
                 ,l.Length
         FROM StartingPositions sp, Lengths l           
         WHERE sp.Position <= LEN(@str)            
    )
-- get only the numbers that start with Dollar Sign, 
-- group by starting position and take the maximum value 
-- (ie, from $, $2, $20, $200 etc)
    SELECT MAX(convert(money, Number)) as Amount
    FROM PossibleCombinations
    WHERE Number like '$%' 
    GROUP BY Position
    )

    GO

    declare @str nvarchar(max) = 'Used knife set for sale $200.00 or best offer.
    $4,500 Persian rug for sale.
    Today only, $100 rebate.
    Five items for sale: $20 Motorola phone car charger, $150 PS2, $50.00 3 foot high shelf.'

    SELECT *
    FROM dbo.fnGetAmounts(@str)
    OPTION(MAXRECURSION 32767) -- max recursion option is required in the select that uses this function

This link should help.

http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/extracting-numbers-with-sql-server

Assuming you are OK with extracting the numeric's, regardless of wether or not there is a $ sign. If that is a strict requirement, some mods will be needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!