【问题标题】:how to parse on column and add more records to a table?如何解析列并向表中添加更多记录?
【发布时间】:2012-09-11 16:19:25
【问题描述】:

我有表 tb1(col1, col2),col2 是 varchar(50)。例如,

col1    col2
item1   abc
item2   a
item3   ed

我想编写一个存储过程来解析 col2 并创建一个临时表,如下所示:

col1    col2
item1   a
item1   b
item1   c
item2   a
item3   e
item3   d

有人可以帮帮我吗?

【问题讨论】:

  • 所以你不在乎从 col2 中识别字符的顺序?

标签: sql sql-server sql-server-2008 stored-procedures


【解决方案1】:

如果你知道字符串的最大长度,最简单的方法是做一个简单的联合:

select col1, substring(col2, 1, 1) as col2
from t
where len(col2) >= 1 union all
select col1, substring(col2, 2, 1) as col2
from t
where len(col2) >= 2 union all
select col1, substring(col2, 3, 1) as col2
from t
where len(col2) >= 3 union all

如果长度永远不会太长,您可以执行以下操作来简化查询:

select col1, substring(col2, nums.seqnum) as col2
from t cross join
     (select row_number() over (order by (select NULL)) as seqnum
      from Infromation_Schema.columns
     ) nums
where len(col2) <= nums.seqnum

或者,您可以在 T-SQL 的 while 循环中执行此操作。

【讨论】:

    【解决方案2】:

    试试这个:

    您可以使用单个查询获取它

    SELECT COL1,SUBSTRING(COL2,NUMBER+1,1) AS COL2
    FROM   YOURTABLE T
    JOIN   MASTER..SPT_VALUES M
    ON     LEN(COL2)>NUMBER
    WHERE  M.TYPE='P'
    

    【讨论】:

    • 这是系统表 MASTER..SPT_VALUES 中的一列
    • @GaolaiPeng:你用的是哪个版本的sql-server?
    猜你喜欢
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 2019-03-08
    相关资源
    最近更新 更多