开发者

Extract table data using split of column values

开发者 https://www.devze.com 2023-02-09 09:52 出处:网络
I have a table data as col1col2col3col4 1112xx yy20 2213qq aa21 my TDD requried using TSQL as col1col2col3col4

I have a table data as

col1    col2    col3   col4
11       12     xx yy    20
22       13     qq aa    21

my TDD requried using TSQL as

col1     col2    col3    col4
11       12       xx      20
11       12       yy      20
22       13       qq      21
22       开发者_JS百科13       aa      21

basically, col3 is having values with space, need to create the rows for each value separed by space value.

thanks prav


Have a look at something like this

DECLARE @Table TABLE(
        col1 INT,
        col2 INT,
        col3 VARCHAR(50),
        col4 INT
)

INSERT INTO @Table SELECT  11,12,'xx yy',20  
INSERT INTO @Table SELECT  22,13,'qq aa',21

;WITH Vals AS (
    SELECT  *,
            CAST('<d>' + REPLACE(col3, ' ', '</d><d>') + '</d>' AS XML) XMLCol
    FROM    @Table
)
SELECT  Vals.*,
        T.split.value('.', 'VARCHAR(MAX)') SplitValue
FROM    Vals
CROSS APPLY
        XMLCol.nodes('/d') T(split)
0

精彩评论

暂无评论...
验证码 换一张
取 消