更好的SQL查询,根据模式拆分字母数字字符串

时间:2015-02-19 10:49:44

标签: sql sql-server sql-server-2008

我需要分割像'20A30D40I10O'这样的字母数字字符串,如下所示。允许的字符:A,D,I,O以任何顺序及其相应的百分比。

+------+------+
| ColA | ColB |
+------+------+
|   20 | A    |
|   30 | D    |
|   40 | I    |
|   10 | O    |
+------+------+

我曾尝试为此编写查询。

DECLARE @Val Varchar(100)
set @Val = '20A30D40I10O'

DECLARE @origTable TABLE(name VARCHAR(1000))
INSERT INTO @origTable(name) VALUES(@Val)

    SELECT SUBSTRING(name,1,2),SUBSTRING(name,3,1)FROM @origTable where name LIKE '%[0-9][0-9]%' and (SUBSTRING(name,3,1) LIKE 'A' OR SUBSTRING(name,3,1) LIKE 'D' OR SUBSTRING(name,3,1) LIKE 'I' OR SUBSTRING(name,3,1) LIKE 'O')
    UNION ALL
    SELECT SUBSTRING(name,4,2),SUBSTRING(name,6,1) FROM @origTable where name LIKE '%[0-9][0-9]%' and (SUBSTRING(name,6,1) LIKE 'A' OR SUBSTRING(name,6,1) LIKE 'D' OR SUBSTRING(name,6,1) LIKE 'I' OR SUBSTRING(name,6,1) LIKE 'O')
    UNION ALL
    SELECT SUBSTRING(name,7,2),SUBSTRING(name,9,1) FROM @origTable where name LIKE '%[0-9][0-9]%' and (SUBSTRING(name,9,1) LIKE 'A' OR SUBSTRING(name,9,1) LIKE 'D' OR SUBSTRING(name,9,1) LIKE 'I' OR SUBSTRING(name,9,1) LIKE 'O')
    UNION ALL
    SELECT SUBSTRING(name,10,2),SUBSTRING(name,12,1) FROM @origTable where name LIKE '%[0-9][0-9]%' and (SUBSTRING(name,12,1) LIKE 'A' OR SUBSTRING(name,12,1) LIKE 'D'OR SUBSTRING(name,12,1) LIKE 'I' OR SUBSTRING(name,12,1) LIKE 'O')

但是如果字符串包含1位数百分比,则此查询不足以拆分字符串。例如:'98D2O'

2 个答案:

答案 0 :(得分:1)

使用while循环和一些string函数。可能不是最好的方法,但应该工作。试试这个。

DECLARE @Val  VARCHAR(100),@cnt  INT =1,@temp VARCHAR(50),@len  INT,@intr INT=1

SET @Val = '20A30D40I10O'
SET @len = Len(@Val)

DECLARE @origTable TABLE
  (name VARCHAR(1000))

WHILE @cnt <= @len
  BEGIN
      SET @temp =Substring(@Val, @cnt, 1)
      IF @temp LIKE '[a-z]'
        BEGIN
            INSERT INTO @origTable
            SELECT Substring(@Val, @intr, ( @cnt - @intr ) + 1)

            SET @intr = @cnt + 1
        END
      SET @cnt=@cnt + 1
  END

SELECT LEFT(name, Patindex('%[a-z]%', name) - 1) Cola,
       Substring(name, Patindex('%[a-z]%', name), Len(name)) Colb
FROM   @origTable 

答案 1 :(得分:0)

我做了一个工作。但是我知道这已经很晚了。我只想分享我所做的事情。

CREATE TABLE #Temp(ColA INT, ColB VARCHAR(20))

DECLARE @TempString VARCHAR(100)
SET @TempString = '20A30D40I10O'
DECLARE @TempVAL VARCHAR(10)
DECLARE @Position INT
DECLARE @Col1Val VARCHAR(10)
SET @Position = 1

WHILE (@Position <= LEN(@TempString))
BEGIN
  SET @TempVAL = SUBSTRING(@TempString, @Position, 1)

  IF(ISNUMERIC(@TempVAL) = 1)
     SET @Col1Val = ISNULL(@Col1Val, '') + @TempVAL
  ELSE
  BEGIN
     INSERT INTO #Temp VALUES(@Col1Val, @TempVAL) 

     SET @Col1Val = NULL
  END
  SET @Position = @Position + 1

END

SELECT * FROM #Temp