Click here to Skip to main content
15,902,900 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

My requirement is to create dymanic(no.of columns may change) Temporary table inside stored procedure in sql server.In my temporary table 4 columns are static(never change in future) remaining are dynamic(may change in future).

four static columns are as follows:
CVRelID,CustomerID,VendorID and TransactionID

The following is query to get dynamic columns form table tblSupportDocuments:

SELECT SDID,SDName,SDIsActive FROM tblSupportDocuments WHERE SDIsActive=1


Dynamic column names should be as SDName values from table tblSupportDocument.
for example: SuppDoct1,SuppDoct2......,SuppDoct3 etc....


please anybody give me some sample code to acheive my requirement.

Thanks in advance

Uday
Posted

You want to google "t-SQL dynamic SQL".
 
Share this answer
 
Your problem can be solved using pivot table in sql
search for sql server pivot query
 
Share this answer
 
This is how you create dynamic columns.
Because I don't have your table structure I cannot help you how to fill the temp table.

SQL
IF OBJECT_ID( 'tempdb..#temp') IS NOT NULL
    BEGIN
    DROP TABLE #temp
    END
CREATE TABLE #temp
    (
    [CVRelID]       INT,
    [CustomerID]    INT,
    [VendorID]      INT,
    [TransactionID] INT
    )

DECLARE @script VARCHAR(8000)
SET     @script = 'ALTER TABLE #temp ADD '

SELECT  @script = @script + QUOTENAME(SDName) + ' VARCHAR(100),'
FROM    tblSupportDocuments
WHERE   SDIsActive = 1


SET     @script = SUBSTRING( @script, 1, LEN(@script) - 1)-- remove last ","
PRINT   @script
EXEC    (@script)
 
Share this answer
 
Comments
udaysimha 24-Sep-11 8:43am    
Hi Costica,

Thanks for your`s replay boss,please can you explain the use of QUOTENAME() function and how it will be usefull for my requirement here.
Costica U 24-Sep-11 19:19pm    
SDName may have invalid char for the column name, e.g. "Supp Doc 1"
QUOTENAME will make it [Supp Doc 1].

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900