Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase 123»»»

need help transforming a table's column to rows Expand / Collapse
Author
Message
Posted Saturday, June 20, 2009 2:42 PM
Valued Member

Valued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued Member

Group: General Forum Members
Last Login: Wednesday, March 19, 2014 8:47 PM
Points: 55, Visits: 132
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!
Post #738904
Posted Saturday, June 20, 2009 4:30 PM


SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Sunday, November 4, 2012 12:23 PM
Points: 1,893, Visits: 3,932
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
Post #738921
Posted Saturday, June 20, 2009 4:47 PM


SSCertifiable

SSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiable

Group: General Forum Members
Last Login: Yesterday @ 3:58 PM
Points: 5,359, Visits: 8,921
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 = '<rows><row>' + replace(ColumnB, ':', '</row><row>') + '</row></rows>'

-- 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
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
Post #738922
Posted Saturday, June 20, 2009 5:01 PM
Valued Member

Valued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued Member

Group: General Forum Members
Last Login: Wednesday, March 19, 2014 8:47 PM
Points: 55, Visits: 132
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!
Post #738924
Posted Saturday, June 20, 2009 8:45 PM
Valued Member

Valued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued Member

Group: General Forum Members
Last Login: Wednesday, March 19, 2014 8:47 PM
Points: 55, Visits: 132
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!
Post #738945
Posted Saturday, June 20, 2009 9:18 PM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Yesterday @ 11:28 PM
Points: 35,263, Visits: 31,750
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."

(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #738952
Posted Saturday, June 20, 2009 9:41 PM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Yesterday @ 11:28 PM
Points: 35,263, Visits: 31,750
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."

(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #738955
Posted Saturday, June 20, 2009 9:44 PM
Valued Member

Valued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued MemberValued Member

Group: General Forum Members
Last Login: Wednesday, March 19, 2014 8:47 PM
Points: 55, Visits: 132
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?
Post #738956
Posted Saturday, June 20, 2009 9:53 PM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Yesterday @ 11:28 PM
Points: 35,263, Visits: 31,750
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.

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."

(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #738958
Posted Saturday, June 20, 2009 9:58 PM


SSCertifiable

SSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiableSSCertifiable

Group: General Forum Members
Last Login: Yesterday @ 3:58 PM
Points: 5,359, Visits: 8,921
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.


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...


Wayne
Microsoft Certified Master: SQL Server 2008
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
Post #738960
« Prev Topic | Next Topic »

Add to briefcase 123»»»

Permissions Expand / Collapse