【问题标题】:SQL Server ParsingSQL Server 解析
【发布时间】:2017-03-23 05:44:39
【问题描述】:

我在一列中有如下分号分隔的数据。我想在单独的行中解析它。

9000389003; 9000389000; 9000389093; 9000383895; 9000490984; 9000389000 9000490980; 9000593580; 9000593599; 9000498085; 9000389003; 9000593580; 9000490990
9000489405; 9000435334; 9000535090; 9000995990

【问题讨论】:

标签: sql-server


【解决方案1】:

在 SQL Server 2016+ 中,您可以使用 string_split()

在 2016 年之前的 SQL Server 中,使用 Jeff Moden 的 CSV Splitter 表值函数:

create table t (id int not null identity(1,1), str varchar(8000));
insert into t values 
  ('9000389003; 9000389000; 9000389093; 9000383895; 9000490984; 9000389000')
 ,('9000490980; 9000593580; 9000593599; 9000498085; 9000389003; 9000593580; 9000490990') 
 ,('9000489405; 9000435334; 9000535090; 9000995990');

select 
    t.id
  , s.ItemNumber
  , Item = ltrim(s.Item)
from t
  cross apply [dbo].[delimitedsplit8K](t.str,';') as s

rextester 演示http://rextester.com/AVQL94047

返回:

+----+------------+------------+
| id | ItemNumber |    Item    |
+----+------------+------------+
|  1 |          1 | 9000389003 |
|  1 |          2 | 9000389000 |
|  1 |          3 | 9000389093 |
|  1 |          4 | 9000383895 |
|  1 |          5 | 9000490984 |
|  1 |          6 | 9000389000 |
|  2 |          1 | 9000490980 |
|  2 |          2 | 9000593580 |
|  2 |          3 | 9000593599 |
|  2 |          4 | 9000498085 |
|  2 |          5 | 9000389003 |
|  2 |          6 | 9000593580 |
|  2 |          7 | 9000490990 |
|  3 |          1 | 9000489405 |
|  3 |          2 | 9000435334 |
|  3 |          3 | 9000535090 |
|  3 |          4 | 9000995990 |
+----+------------+------------+

拆分字符串参考:

【讨论】:

  • @MaverikAnderson 很高兴为您提供帮助!
【解决方案2】:

如果您不能为string_split() 使用 SQL-Server 2016,或者如果您不允许创建新函数,或者如果您只是想要一个简单的 ad-hoc 方法,您可以这样做:

DECLARE @tbl TABLE(id int not null identity, YourString varchar(1000));
INSERT INTO @tbl VALUES 
  ('9000389003; 9000389000; 9000389093; 9000383895; 9000490984; 9000389000')
 ,('9000490980; 9000593580; 9000593599; 9000498085; 9000389003; 9000593580; 9000490990') 
 ,('9000489405; 9000435334; 9000535090; 9000995990');

 WITH Casted AS
 (
    SELECT t.id 
          ,CAST('<x>' + REPLACE(YourString,';','</x><x>') + '</x>' AS XML) AsXml
    FROM @tbl AS t
 )
 SELECT id
       ,nodes.value('(./text())[1]','bigint') AS TheNumber
 FROM Casted
 CROSS APPLY Casted.AsXml.nodes('/x') AS The(nodes)

一个优势可能是 - 除了通常的字符串拆分器方法 - 您可以输入键入的值(在这种情况下为 bigint)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 2013-03-18
    • 2020-04-09
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多