Click here to monitor SSC
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 


need help transforming a table's column to rows


need help transforming a table's column to rows

Author
Message
ktlady
ktlady
Valued Member
Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)

Group: General Forum Members
Points: 57 Visits: 140
I have a table (tableA) with following format while Column1 is primary key and Column2 is delimited with ":".
Column1 Column2
a1 1:3:5:6
a2 2:4:5

I'd like to use stored procedure to transform tableA to tableB and insert into tableB as following:
Column1 Column2
a1 1
a1 3
a1 5
a1 6
a2 2
a2 4
a2 5
In case of tableB, the primary key would become Column1 & Column2.

Could someone help me with the T-SQL stored procedure code in handling this?

Thanks a lot!
Florian Reischl
Florian Reischl
SSCommitted
SSCommitted (1.9K reputation)SSCommitted (1.9K reputation)SSCommitted (1.9K reputation)SSCommitted (1.9K reputation)SSCommitted (1.9K reputation)SSCommitted (1.9K reputation)SSCommitted (1.9K reputation)SSCommitted (1.9K reputation)

Group: General Forum Members
Points: 1939 Visits: 3934
You can use a Tally table and CROSS APPLY to scan your text and split for your delimiter.


DECLARE @t TABLE (col1 varchar(10), col2 varchar(30));

INSERT INTO @t
SELECT 'a1', '1:3:5:6'
UNION ALL SELECT 'a2', '2:4:5';

; WITH t1 (col1, col2) AS
(
SELECT
col1,
':' + col2 + ':'
FROM @t
)
SELECT
t1.col1,
t2.Item
FROM t1
CROSS APPLY
(
SELECT
SUBSTRING(t1.col2, N + 1, CHARINDEX(':', t1.col2, N + 1) - N - 1) Item
FROM Tally
WHERE N < LEN(t1.col2)
AND SUBSTRING(t1.col2, N, 1) = ':'
) t2;



If you don't know a Table or how to work with please search this site. You will find a really good article published by Jeff Moden which explains the Tally table and how to use it for requirements like this.

Flo


The more I learn, the more I know what I do not know
Blog: Things about Software Architecture, .NET development and T-SQL

How to Post Data/Code to get the best Help How to Post Performance Problems
WayneS
WayneS
SSCertifiable
SSCertifiable (6.2K reputation)SSCertifiable (6.2K reputation)SSCertifiable (6.2K reputation)SSCertifiable (6.2K reputation)SSCertifiable (6.2K reputation)SSCertifiable (6.2K reputation)SSCertifiable (6.2K reputation)SSCertifiable (6.2K reputation)

Group: General Forum Members
Points: 6234 Visits: 10401
ktlady (6/20/2009)
I have a table (tableA) with following format while Column1 is primary key and Column2 is delimited with ":".
Column1 Column2
a1 1:3:5:6
a2 2:4:5

I'd like to use stored procedure to transform tableA to tableB and insert into tableB as following:
Column1 Column2
a1 1
a1 3
a1 5
a1 6
a2 2
a2 4
a2 5
In case of tableB, the primary key would become Column1 & Column2.

Could someone help me with the T-SQL stored procedure code in handling this?

Thanks a lot!


You can use some xml to do the trick...

-- first make a temp table to hold the sample data
declare @tmp table (
ColumnA char(2),
ColumnB varchar(50),
TmpCol XML NULL) --<<<<< NOTE the new column being added

-- put the sample data into the temp table.
-- NOTICE how this makes it so much easier for people to just copy and start testing
insert into @tmp (ColumnA, ColumnB)
select 'a1', '1:3:5:6' UNION ALL
select 'a2', '2:4:5'

-- update the xml column by replacing the delimiter with XML tags,
-- and putting the appropriate XML tags around the string.
update @tmp
set TmpCol = '' + replace(ColumnB, ':', '') + ''

-- shred the xml data apart into individual rows
select T.ColumnA,
x.data.value('.','int') AS ColumnB
--INTO TABLE2
from @tmp T
CROSS APPLY TmpCol.nodes('/rows/row') AS x(data)



results:

ColumnA ColumnB
a1 1
a1 3
a1 5
a1 6
a2 2
a2 4
a2 5


Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes
If you can't explain to another person how the code that you're copying from the internet works, then DON'T USE IT on a production system! After all, you will be the one supporting it!
Links: For better assistance in answering your questions, How to ask a question, Performance Problems, Common date/time routines,
CROSS-TABS and PIVOT tables Part 1 & Part 2, Using APPLY Part 1 & Part 2, Splitting Delimited Strings

ktlady
ktlady
Valued Member
Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)

Group: General Forum Members
Points: 57 Visits: 140
Flo & Wayne,

Thank you so much! You guys are so quick and I'll try out both ways. Flo's way is more straight-forward to me. I appreciate Wayne's xml way and all it's comments too.

It's a great learning experience from you guys!

Have a great weekend!
ktlady
ktlady
Valued Member
Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)

Group: General Forum Members
Points: 57 Visits: 140
Sorry, I got errors from both scripts. Would you please help again.

The first Flo's script, I got the following error:
Invalid object name 'Tally'.

Second Waynes script, I got empty output with only headers
"ColumnA ColumnB"

Thanks again!
Jeff Moden
Jeff Moden
SSC-Forever
SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)

Group: General Forum Members
Points: 45036 Visits: 39893
Florian Reischl (6/20/2009)
If you don't know a Table or how to work with please search this site. You will find a really good article published by Jeff Moden which explains the Tally table and how to use it for requirements like this.

Flo


Thanks for the plug, Flo. :-) The article on what a Tally table is and how it replaces a loop in many cases, can be found at the following URL...
http://www.sqlservercentral.com/articles/T-SQL/62867/

--Jeff Moden

RBAR is pronounced ree-bar and is a Modenism for Row-By-Agonizing-Row.
First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column.
Although they tell us that they want it real bad, our primary goal is to ensure that we dont actually give it to them that way.
Although change is inevitable, change for the better is not.
Just because you can do something in PowerShell, doesnt mean you should. Wink

Helpful Links:
How to post code problems
How to post performance problems
Forum FAQs
Jeff Moden
Jeff Moden
SSC-Forever
SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)

Group: General Forum Members
Points: 45036 Visits: 39893
As a side bar, for those interested in a Tally table solution that will work in virtually any release of SQL Server...

--===== Build the test table as the data source
 
CREATE TABLE dbo.TableA (Column1 VARCHAR(5), Column2 VARCHAR(30))
 
INSERT INTO dbo.TableA
        
(Column1Column2)
 
SELECT 'a1''1:3:5:6' UNION ALL
 
SELECT 'a2''2:4:5'

--===== Solution for virtually any version of SQL Server
 
INSERT INTO dbo.TableB
        
(Column1Column2)
 
SELECT a.Column1,
        
SUBSTRING(a.Column2t.N+1CHARINDEX(':'a.Column2N+1) - N-1AS Column2
   
FROM dbo.Tally t
  
CROSS JOIN 
        
(SELECT Column1':'+Column2+':' AS Column2 FROM dbo.TableAa
   
WHERE LEN(a.Column2)
     AND 
SUBSTRING(a.Column2N1':'


--Jeff Moden

RBAR is pronounced ree-bar and is a Modenism for Row-By-Agonizing-Row.
First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column.
Although they tell us that they want it real bad, our primary goal is to ensure that we dont actually give it to them that way.
Although change is inevitable, change for the better is not.
Just because you can do something in PowerShell, doesnt mean you should. Wink

Helpful Links:
How to post code problems
How to post performance problems
Forum FAQs
ktlady
ktlady
Valued Member
Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)Valued Member (57 reputation)

Group: General Forum Members
Points: 57 Visits: 140
Jeff, thanks for the pointer. Sorry that I missed it the first time. It sure is a great article! There is so much to learn for SQL server!

Wayne or anyone: How come the 2nd xml script doesn't work? It looks perfectly logical to me. How come I am not getting any output?
Jeff Moden
Jeff Moden
SSC-Forever
SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)SSC-Forever (45K reputation)

Group: General Forum Members
Points: 45036 Visits: 39893
ktlady (6/20/2009)
Jeff, thanks for the pointer. Sorry that I missed it the first time. It sure is a great article! There is so much to learn for SQL server!


It's ok... most folks don't usually have a Tally table when they first hear of it and don't understand that you need to build one. Most think that it comes with SQL Server. :-P

Thanks for the feedback on the article, KT... I appreciate it.

--Jeff Moden

RBAR is pronounced ree-bar and is a Modenism for Row-By-Agonizing-Row.
First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column.
Although they tell us that they want it real bad, our primary goal is to ensure that we dont actually give it to them that way.
Although change is inevitable, change for the better is not.
Just because you can do something in PowerShell, doesnt mean you should. Wink

Helpful Links:
How to post code problems
How to post performance problems
Forum FAQs
WayneS
WayneS
SSCertifiable
SSCertifiable (6.2K reputation)SSCertifiable (6.2K reputation)SSCertifiable (6.2K reputation)SSCertifiable (6.2K reputation)SSCertifiable (6.2K reputation)SSCertifiable (6.2K reputation)SSCertifiable (6.2K reputation)SSCertifiable (6.2K reputation)

Group: General Forum Members
Points: 6234 Visits: 10401
Jeff Moden (6/20/2009)
It's ok... most folks don't usually have a Tally table when they first hear of it and don't understand that you need to build one. Most think that it comes with SQL Server. :-P


You know, as much as it helps out, maybe it ought to. Put a million (edit: or billion) row tally table in master, and people wouldn't have an excuse... w00t

Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes
If you can't explain to another person how the code that you're copying from the internet works, then DON'T USE IT on a production system! After all, you will be the one supporting it!
Links: For better assistance in answering your questions, How to ask a question, Performance Problems, Common date/time routines,
CROSS-TABS and PIVOT tables Part 1 & Part 2, Using APPLY Part 1 & Part 2, Splitting Delimited Strings

Go


Permissions

You can't post new topics.
You can't post topic replies.
You can't post new polls.
You can't post replies to polls.
You can't edit your own topics.
You can't delete your own topics.
You can't edit other topics.
You can't delete other topics.
You can't edit your own posts.
You can't edit other posts.
You can't delete your own posts.
You can't delete other posts.
You can't post events.
You can't edit your own events.
You can't edit other events.
You can't delete your own events.
You can't delete other events.
You can't send private messages.
You can't send emails.
You can read topics.
You can't vote in polls.
You can't upload attachments.
You can download attachments.
You can't post HTML code.
You can't edit HTML code.
You can't post IFCode.
You can't post JavaScript.
You can post emoticons.
You can't post or upload images.

Select a forum

































































































































































SQLServerCentral


Search