【问题标题】:SQL - Parse StringSQL - 解析字符串
【发布时间】:2013-01-04 00:05:49
【问题描述】:

我有一个表格,其中包含:

ID     Names 
1      Aaron, Betsy, Cindy 
2      Dillon, Eric, Fred 

我想解析 name 列并让它返回:

ID   Names 
1    Aaraon 
1    Betsy 
1    Cindy 
2    Dillon 

我在网上找到了几个解析名称列但不将 ID 绑定回它的函数。

【问题讨论】:

  • 您没有建立一对多关系模型是否有特殊原因?或者这个查询是你计划迁移到正确的一对多关系的一部分吗?
  • 您使用的是什么 rdbms? mysql?甲骨文? sql server?...
  • 你用的是什么关系型数据库?
  • 当遇到这样的问题并且您正在使用的rdbms中没有函数时,您可以自己编写该函数或将结果集带入您的客户端程序并后处理结果本地。对于小型数据集,我有时会选择后者,因为它更简单。
  • 您发现返回名称但不返回 id 的示例是什么?

标签: sql sql-server-2012


【解决方案1】:

这样的事情怎么样:

;with cte (id, name, names) as
(
  select id,
    cast(left(names, charindex(',',names+',')-1) as varchar(50)) name,
         stuff(names, 1, charindex(',',names+','), '') names
  from yourtable
  union all
  select id,
    cast(left(names, charindex(',',names+',')-1) as varchar(50)) name,
    stuff(names, 1, charindex(',',names+','), '') names
  from cte
  where names > ''
) 
select id, name
from cte
order by id

SQL Fiddle with Demo

返回结果:

| ID |   NAME |
---------------
|  1 |  Aaron |
|  1 |  Betsy |
|  1 |  Cindy |
|  2 | Dillon |
|  2 |   Eric |
|  2 |   Fred |

【讨论】:

  • @user1411074 乐于助人。如果此答案对您有帮助,请务必通过左侧的复选标记接受。它将帮助该网站的未来访问者,并且您会因接受而获得声誉。
猜你喜欢
  • 2021-03-02
  • 2010-10-13
  • 2021-02-18
  • 2013-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多