Click here to Skip to main content
       

Database

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionInserting rows dynamiccaly on based on calculationmembervkap20 Jun '12 - 11:45 
I have a db with following values :
col1 col2 col3 position
aaa rack1 1-3 3
bbb rack2 22-23 2
ccc rack3 19-20 2
 
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, its taking the 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
AnswerRe: Inserting rows dynamiccaly on based on calculationmemberMycroft Holmes20 Jun '12 - 13:05 
If you are doing this in the database you are going to have to write some code, you can't magic it into the multiple row. I would look at the method of inserting the original record and change or enhance that method.
 
Alternatively you can use an insert trigger spit, I would do this as a last resort.
Never underestimate the power of human stupidity
RAH

AnswerRe: Inserting rows dynamiccaly on based on calculationmemberMember 83389623 Jul '12 - 20:41 
Try this
 
 

CREATE TABLE #Temp
(
	ID INT IDENTITY(1,1),
	col1 VARCHAR(50),
	Col2 VARCHAR(50),
	Col3 VARCHAR(50),
	position VARCHAR(50)
)
 

CREATE TABLE #Temp2
(
	col1 VARCHAR(50),
	Col2 VARCHAR(50),
	Col3 VARCHAR(50),
	position VARCHAR(50)
)
 

 
INSERT INTO #Temp
SELECT 'aaa', 'rack1', '1-3', '3' UNION
SELECT 'bbb', 'rack2', '22-23', '2' UNION
SELECT 'ccc', 'rack3', '19-20', '2' 
 

 
DECLARE @TotalRowCount  INT
DECLARE @RowCount INT
DECLARE @Positon INT
DECLARE @I INT
 
SET @RowCount = 1
 
SELECT @TotalRowCount = COUNT(*) FROM #Temp
 
WHILE @RowCount <= @TotalRowCount
BEGIN
 
	SELECT @Positon = Position FROM #Temp WHERE Id = @RowCount
 
	SET @I = 1
 
	WHILE @I <= @Positon
	BEGIN
 
		INSERT INTO #Temp2
		SELECT Col1, Col2, Col3, (SUBSTRING(Col3,0,CHARINDEX('-',Col3)) + @I - 1) FROM #Temp  WHERE Id = @RowCount
		
		SET @I = @I + 1
	END
	
	SET @RowCount = @RowCount + 1
	
END
 
SELECT * FROM #Temp2
 

 
DROP TABLE #Temp
DROP TABLE #Temp2

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   


Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 17 May 2013
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid