December 15, 2009 at 10:43 pm
Hi all
Good morning.:-)
I have data in a table(group id is a identity column) like
group id code
1 123,126,139,203
2 126,139,203
3 303
I want to write a single query to store data in a temporary table like
group id code
1 123
1 126
1 139
1 203
2 126
2 139
2 203
3 303
Can any body help me?
Thanks in advance.
December 15, 2009 at 11:03 pm
Hi,
Ref the jeff article The "Numbers" or "Tally" Table: What it is and how it replaces a loop
http://www.sqlservercentral.com/articles/T-SQL/62867/
From this,
CREATE TABLE #temp
(ID INT, ITEM1 VARCHAR(100))
GO
INSERT #temp
SELECT 1,'123,126,139,203'
UNION all
SELECT 2,'126,139,203'
UNION all
SELECT 3,'303'
/*create the TALLY table*/
SELECT TOP 11000 --equates to more than 30 years of dates
IDENTITY(INT,1,1) AS N INTO Tally
FROM Master.dbo.SysColumns sc1,
Master.dbo.SysColumns sc2
ALTER TABLE Tally ADD CONSTRAINT PK_Tally_N PRIMARY KEY CLUSTERED (N) WITH FILLFACTOR = 100
SELECT b.ID, SUBSTRING(','+b.ITEM1+',',N+1,CHARINDEX(',',','+b.ITEM1+',',N+1)-N-1) AS Value
FROM Tally a
CROSS JOIN #temp b
WHERE N < LEN(','+b.ITEM1+',')
AND SUBSTRING(','+b.ITEM1+',',N,1) = ','
December 15, 2009 at 11:43 pm
Thanks Arun,
I have tested with test data. It is working. I will try with real data. Thanks alot for your solution.
December 15, 2009 at 11:57 pm
Hi,
The solution based on the jeff article mentioned above, with your real data you should mine with this article to get more.
December 18, 2009 at 2:25 am
A variation on arun's solution above with fewer string concatenations:
SELECT
ID, substring(item1,N,charindex(',',item1+',',N)-N)
FROM
tally
CROSS JOIN
#temp
WHERE
N <= LEN(item1)+1 AND
(N = 1 OR SUBSTRING(item1,N-1,1)=',')
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply