SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Inserting rows and columns based on column values
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

vkap
Starting Member

3 Posts

Posted - 06/20/2012 :  17:48:01  Show Profile  Reply with Quote
I have a tble with following values :
col1 col2 col3
aaa rack1 1-3
bbb rack2 22-23
ccc rack3 19-20

Output should be
col1 col2 col3 position
aaa rack1 1-3 1
aaa rack1 1-3 2
aaa rack1 1-3 3
bbb rack2 22-23 22
bbb rack2 22-23 23
ccc rack3 19-20 19
ccc rack3 19-20 20

Basically, i need a new column 'Position' and creating a row for each value from col3.

Can i do this on-fly and create a temp table? or i have to create a procedure?

thanks!!!
VK

Edited by - vkap on 06/20/2012 18:01:56

Lamprey
Flowing Fount of Yak Knowledge

3829 Posts

Posted - 06/20/2012 :  18:04:31  Show Profile  Reply with Quote
You could use a Number or Tally table. Here is one way to do it with an inline-tally table:
DECLARE @T TABLE (col1 varchar(3), col2 varchar(10), col3 varchar(10))
INSERT @T VALUES
('aaa', 'rack1', '1-3'),
('bbb', 'rack2', '22-23'), 
('ccc', 'rack3', '19-20')


;WITH 
Tens (N)     AS (SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL
                 SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9), 
Thousands(N) AS (SELECT t1.N FROM Tens t1 CROSS JOIN Tens t2 CROSS JOIN Tens t3), 
Millions (N) AS (SELECT t1.N FROM Thousands t1 CROSS JOIN Thousands t2), 
Tally (N)    AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) FROM Millions)

SELECT
	A.*,
	T.N As Position
FROM
	@T AS A	
INNER JOIN
	Tally AS T
	ON T.N BETWEEN CAST(PARSENAME(REPLACE(col3, '-', '.'), 2) AS INT)  AND CAST(PARSENAME(REPLACE(col3, '-', '.'), 1) AS INT)
Go to Top of Page

vkap
Starting Member

3 Posts

Posted - 06/21/2012 :  12:51:01  Show Profile  Reply with Quote
thanks Lamprey, it works really well!!! very nice suggestion!!
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000