简体   繁体   中英

Select to Return Multiple Rows from Single Row

I am working on a query that returns a list of items shown below:

SELECT ID, Description FROM TableA WHERE ID = 10001

Returns:

ID     Description
10001  Item1 Item2 Item3 Item4

However, what I want is to be able to make the return multiple rows.

ID     Description
10001  Item1 
10001  Item2 
10001  Item3 
10001  Item4

Is there an easy way to achieve this?

Thank you!

Here is how you can do this:

SELECT id,
   Split.a.value('.', 'VARCHAR(100)') AS String  
FROM  (SELECT id, CAST ('<M>' + REPLACE(description, ' ', '</M><M>') + '</M>' AS XML) AS n from TableA where id = 1001) AS A 
CROSS APPLY n.nodes ('/M') AS Split(a); 

Fiddle http://sqlfiddle.com/#!3/152e3/1

You can also create a function to do that as such

CREATE FUNCTION [dbo].[RowToManyRows] ( @StringInput VARCHAR(8000) )
RETURNS @OutputTable TABLE ( [String] VARCHAR(10) )
AS
BEGIN

    DECLARE @String    VARCHAR(10)

    WHILE LEN(@StringInput) > 0
    BEGIN
        SET @String      = LEFT(@StringInput, 
                                ISNULL(NULLIF(CHARINDEX(' ', @StringInput) - 1, -1),
                                LEN(@StringInput)))
        SET @StringInput = SUBSTRING(@StringInput,
                                     ISNULL(NULLIF(CHARINDEX(' ', @StringInput), 0),
                                     LEN(@StringInput)) + 1, LEN(@StringInput))

        INSERT INTO @OutputTable ( [String] )
        VALUES ( @String )
    END

    RETURN
END
GO

You then query that function as such

SELECT ID, String
FROM myTable CROSS APPLY [dbo].RowToManyRows(myTable.Description)

Example:

CREATE TABLE myTable 
( ID INT, 
   Description VARCHAR(50)
 )

 INSERT INTO dbo.myTable
         ( ID, Description )
 VALUES  ( 1, -- ID - int
           'A B'  -- Description - varchar(50)
         ),
         (2, 
         'C D')

Results

1   A
1   B
2   C
2   D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM