SQL从Varchar列中提取特定值&将这些列值拆分为行

时间:2018-03-27 16:41:55

标签: sql-server function tsql cursor

我已尝试执行以下代码&它抛出错误

  

Msg 2809,   对过程'SplitStringTest'的请求失败,因为'SplitStringTest'是一个表值函数对象。“

DECLARE @ID INT
DECLARE @Name VARCHAR(MAX)
DECLARE @opt VARCHAR(MAX)
DECLARE CursorTest CURSOR
   FOR SELECT ID, 
Name, 
dbo.RemoveCharacterswithoutspacesTest(Desc) as opt
FROM input_table
OPEN CursorTest

      FETCH NEXT FROM CursorTest
            INTO @ID,@Name, @opt
      WHILE @@FETCH_STATUS = 0
            BEGIN 
                  EXEC SplitStringTest @opt
            FETCH NEXT FROM CursorTest
                  INTO @ID, @Name, @opt
            END         


CLOSE CursorTest
DEALLOCATE CursorTest

我正在寻找SQL Server中的解决方案,如下所示

当前表:

ID    Name    Desc
-----------------------
123   KR      difference 76887 ghfr 88888063 7282
456    CD     088724   see there  29851  bus 0012

预期产出:

ID    NAME    DESC
-----------------------
123    KR     76887
123    KR     88888063
123    KR     7282
456    CD     088724
456    CD     29851
456    CD     0012

2 个答案:

答案 0 :(得分:0)

SQL Server(从2016年开始)

SELECT ID, Name, value  
FROM Table1  
CROSS APPLY STRING_SPLIT([desc], ' ')
WHERE ISNUMERIC(value)=1;  

输出

ID  Name  value
123 KR    76887
123 KR    88888063
123 KR    7282
456 CD    088724
456 CD    29851
456 CD    0012

现场演示

  

http://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=f049720899f7a106c83ae7c02bfbde32

答案 1 :(得分:0)

当您使用属于Oracle的PL / SQL标记标记它时,这是一个选项:

SQL> with test (id, name, descr) as
  2    (select 123, 'KR', 'difference 76887 ghfr 88888063 7282' from dual union
  3     select 456, 'CD', '088724   see there  29851  bus 0012' from dual
  4    )
  5  select id, name,
  6    regexp_substr(descr, '\d+', 1, column_value) descr
  7  from test,
  8       table(cast(multiset(select level from dual
  9                           connect by level <= regexp_count(descr, ' ') + 1
 10                          ) as sys.odcinumberlist))
 11  where regexp_like(regexp_substr(descr, '\d+', 1, column_value), '\d+')
 12  order by id, name;

        ID NAME       DESCR
---------- ---------- ----------
       123 KR         76887
       123 KR         88888063
       123 KR         7282
       456 CD         088724
       456 CD         29851
       456 CD         0012

6 rows selected.

SQL>