Using PATINDEX to find varying length patterns in T-SQL

后端 未结 6 2121
旧时难觅i
旧时难觅i 2020-12-19 01:20

I\'m looking to pull floats out of some varchars, using PATINDEX() to spot them. I know in each varchar string, I\'m only interested in the first float that exists, but they

6条回答
  •  轮回少年
    2020-12-19 02:25

    Given that the pattern is going to be varied in length, you're not going to have a rough time getting this to work with PATINDEX. There is another post that I wrote, which I've modified to accomplish what you're trying to do here. Will this work for you?

    CREATE TABLE #nums (n INT)
    DECLARE @i INT 
    SET @i = 1
    WHILE @i < 8000 
    BEGIN
        INSERT #nums VALUES(@i)
        SET @i = @i + 1
    END
    
    CREATE TABLE #tmp (
      id INT IDENTITY(1,1) not null,
      words VARCHAR(MAX) null
    )
    
    INSERT INTO #tmp
    VALUES('I''m looking for a number, regardless of length, even 23.258 long'),('Maybe even pi which roughly 3.14159265358,'),('or possibly something else that isn''t a number')
    
    UPDATE #tmp SET words = REPLACE(words, ',',' ')
    
    ;WITH CTE AS (SELECT ROW_NUMBER() OVER (ORDER BY ID) AS rownum, ID, NULLIF(SUBSTRING(' ' + words + ' ' , n , CHARINDEX(' ' , ' ' + words + ' ' , n) - n) , '') AS word
        FROM #nums, #tmp
        WHERE ID <= LEN(' ' + words + ' ') AND SUBSTRING(' ' + words + ' ' , n - 1, 1) = ' ' 
        AND CHARINDEX(' ' , ' ' + words + ' ' , n) - n > 0),
        ids AS (SELECT ID, MIN(rownum) AS rownum FROM CTE WHERE ISNUMERIC(word) = 1 GROUP BY id)
    SELECT CTE.rownum, cte.id, cte.word
    FROM CTE, ids WHERE cte.id = ids.id AND cte.rownum = ids.rownum
    

    The explanation and origin of the code is covered in more detail in the origional post

提交回复
热议问题