拆分一列的逗号分隔值,并使用现有数据生成新行 [英] Split comma seprated value of a column and generate a new row with existing data

查看:85
本文介绍了拆分一列的逗号分隔值,并使用现有数据生成新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我在sql server中有一张表,其中一列有逗号分隔值,我想为每个逗号分隔值生成一个新行.例如.

表格:

 col1 col2 col3
----------------------------
     1 45 7
     2 48 6,7
     3 46 4 




输出应为:

 col1 col2 col3
----------------------------
     1 45 7
     2 48 6
     2 48 7
     3 46 4 



预先感谢.

解决方案

使用此代码拆分值并编写存储过程以存储,

 创建 功能 [dbo].[fn_Split]( @列表  nvarchar (MAX))
   返回  @ tbl   TABLE (数字 int    NULL )开始
    DECLARE   @ pos   int  @ nextpos   int  @ valuelen   int 
  
   选择  @ pos  =  0  @ nextpos  =  1 
  
   全部  @ nextpos >  0 
   开始
      选择  @ nextpos  = charindex(' ,' @ list  @ pos  +  1 )
      选择  @ valuelen  = 案例 何时  @ nextpos >  0 
                              时间  @ nextpos 
                               ELSE  len( @ list )+  1 
                          END - @ pos - 1 
      插入  @ tbl (数字)
         (转换( int ,子字符串(  @列表 @ pos  +  1  @ valuelen )))
      选择  @ pos  =  @ nextpos 
    END 
  返回
 END 
  
- 从dbo.fn_Split('1,2,3') 

<中选择* /blockquote>

请参阅此参考资料 http: //stackstackflow.com/questions/5493510/turning-a-comma-separated-string-into-individual-rows [ col1 col2 col3 ---------------------------- 1 45 7 2 48 6,7 3 46 4




output should be :

    col1    col2   col3
----------------------------
     1       45     7
     2       48     6
     2       48     7
     3       46     4



Thanks in advance.

解决方案

hi, use this code to split the value and write a stored procedure to store,

Create FUNCTION [dbo].[fn_Split] (@list nvarchar(MAX))  
   RETURNS @tbl TABLE (number int NOT NULL) AS  
BEGIN  
   DECLARE @pos        int,  
           @nextpos    int,  
           @valuelen   int  
  
   SELECT @pos = 0, @nextpos = 1  
  
   WHILE @nextpos > 0  
   BEGIN  
      SELECT @nextpos = charindex(',', @list, @pos + 1)  
      SELECT @valuelen = CASE WHEN @nextpos > 0  
                              THEN @nextpos  
                              ELSE len(@list) + 1  
                         END - @pos - 1  
      INSERT @tbl (number)  
         VALUES (convert(int, substring(@list, @pos + 1, @valuelen)))  
      SELECT @pos = @nextpos  
   END  
  RETURN  
END  
  
-- Select * from dbo.fn_Split('1,2,3')


Please see this reference http://stackoverflow.com/questions/5493510/turning-a-comma-separated-string-into-individual-rows[^] where answer to a similar question is given.


这篇关于拆分一列的逗号分隔值,并使用现有数据生成新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆