如何仅使用SQL为表中的每一行生成多行

时间:2012-01-13 20:40:03

标签: sql oracle

  

可能重复:
  Split column to multiple rows

我有表包含以下数据: -

Name
---------
mouse,keyboard,screen
harddisk,cable
processor

我需要创建查询以从此表中检索数据,如下所示: -

Name
--------
mouse
keyboard
screen
harddisk
cable
processor

2 个答案:

答案 0 :(得分:0)

首先,您需要一个分割功能,例如:http://blog.logiclabz.com/sql-server/split-function-in-sql-server-to-break-comma-separated-strings-into-table.aspx

然后你可以运行:

  select *
  from MyTable t
  cross apply dbo.Split(t.name) s

和s.items将包含您想要的内容。

答案 1 :(得分:0)

试试这个:

    DECLARE @t TABLE (Item VARCHAR(64))
    DECLARE @spot SMALLINT, @str VARCHAR(8000), @sql VARCHAR(8000), @cslist VARCHAR(8000)

    SELECT @cslist = mouse + ',' + keyboard,screen + ',' + harddisk + ',' + cable + ',' + processor
FROM Table

        WHILE @cslist <> ''  
        BEGIN  
            SET @spot = CHARINDEX(',', @cslist)

            IF @spot > 0  
                BEGIN  
                    SET @str = LEFT(@cslist, @spot - 1)  
                    SET @cslist = RIGHT(@cslist, LEN(@cslist) - @spot)  
                END  
            ELSE  
                BEGIN  
                    SET @str = @cslist  
                    SET @cslist = ''  
                END  
            INSERT @t SELECT @str

    SELECT * FROM @t