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)
 HOw to create a table with dynamic column names

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2007-03-07 : 08:45:01
Moupiya writes "I want to create a table (#temp or local temp)
Something like

[ID,Name,@sql]
@sql can be a,b,c,d or @sql can be X,Y,Z


My problem is i can create a table of this kind. But not able to perform any operation on it.

I can create this using dynamic SQL but if afterwards i want to update the same table based on some conditions i cannot do so.The table becomes an invalid object.

How can i solve this kind of problem.

Example:

declare @sql varchar(100)
declare @TableColumnName varchar(100)
set @TableColumnName ='WK1 int,WK2 int'
set @sql='declare @local_Table table(ID int,Name varchar(10)'+ @TableColumnName +')'

declare @InsertData varchar(100)

set @InsertData ='Insert into'+@local_Table +' select ID,Name,Wk1,Wk2 from Table1'

exec (@sql+@InsertData)

while(some condition)
begin
----- HERE I Want to update the @local table.
end


The syntax may not correct exactly. Tell me some other alternative of doing this."

spirit1
Cybernetic Yak Master

11752 Posts

Posted - 2007-03-07 : 09:22:52
first tell us what problem do you have to solve that would require such a solution?
because this is not very good db design.

Causing trouble since 1980
blog: http://weblogs.sqlteam.com/mladenp
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2007-03-07 : 09:29:11
use temp table instead of table variable.


KH

Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2007-03-07 : 09:30:40
Just continue down the dark path.

Use 1 local variable and just keep assigning your script.

What you do with that then, I have no idea



Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

Add yourself!
http://www.frappr.com/sqlteam



Go to Top of Page
   

- Advertisement -