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 2000 Forums
 SQL Server Development (2000)
 table with a dynamic number of columns

Author  Topic 

Clages1
Yak Posting Veteran

69 Posts

Posted - 2007-01-03 : 15:59:08
hi

i have a table named moviment like this

Store - Goods - Invoice - date - qty - etc
01 123 4567 xxxx 10
01 123 6545 xxxx 15
04 123 66464 xxxx 20
09 344 4542 xxxx 33
..
..


I can have up to 300 stores cross the country

i would like to create a New table named SALDO like this
since the user can choose how many stores he wants.
if he choose 3 the table should be 3 columns
if he choose 44 the table should be 44 columns
and so on

Goods Store01 Store02 Store03 Store04 .... store09 storeNN
123 25 0 0 20 0
344 0 0 0 0 33


as i can have more than 300 stores and
i would not like to create a table with 300 columns

what is the best solutions to create only the columns (stores) that have balance <> 0 ?

tks

C. lages

snSQL
Master Smack Fu Yak Hacker

1837 Posts

Posted - 2007-01-03 : 16:15:03
You mustn't create a table with a dynamic number of columns. What is the table for? If you just want a list of balances for a selected number of stores, write a query like this

SELECT Goods, Store, sum(qty) AS SALDO
FROM moviment
GROUP BY Goods, Store

If you really want a copy of the data in another table (and I'm pretty sure you don't because then you have to keep it updated whenever the source data changes), then create a table with a similar structure to the query I gave you (columns for Goods, Store and Saldo).

If you want to report that data with stores as columns then you can either do that in a reporting tool like SQL Server Reporting Services or Crystal Reports, or you can write a cross-tab query. For cross-tab queries, you can use the PIVOT clause of the SELECT statement on SQL Server 2005, or see here for a way to do it on SQL Server 2000
http://sqlteam.com/item.asp?ItemID=2955
Go to Top of Page
   

- Advertisement -