Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Insert into column based on its ordering number

Author  Topic 

Wodzu
Yak Posting Veteran

58 Posts

Posted - 2009-06-24 : 08:57:24
Hi.

I have table like this:


CREATE TABLE dbo.#MyTable (
Column1 decimal(15,2), --
Column2 decimal(15,2),
Column3 decimal(15,2),
Column4 decimal(15,2),
Column5 decimal(15,2),
...
ColumnN decimal(15,2)
)


How to insert data to a given column but I do not know which column it will be during query execution.

For example, firstly I calculate two values, @ColumnNumber, @Price

and now I would like to insert @Price into dbo.#MyTable into column which order number (in table) is equal to a @ColumnNumber.

I don't want to do it like this:


CASE @ColumnNumber
WHEN 1 THEN BEGIN INSERT INTO dbo.#MyTable Column1 VALUES(@Price) END
WHEN 2 THEN BEGIN INSERT INTO dbo.#MyTable Column2 VALUES(@Price) END
WHEN N THEN BEGIN INSERT INTO dbo.#MyTable ColumnN VALUES(@Price) END
END


Is there other solution?

Thanks for your time.

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2009-06-24 : 09:20:17
You can use dynamic sql, if all columns follow the same naming convention rules.

But your best bet would be to NORMALIZE your table structure. When you have done that, all you need to do is

INSERT MyNewAndBetterTable (ColNum, ColValue)
VALUES (@ColumnNumber, @Price)

Read here about normalization of tables
http://www.datamodel.org/NormalizationRules.html



E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page
   

- Advertisement -