Dynamic creation of table in tsql

守給你的承諾、 提交于 2019-12-13 06:39:07

问题


I am trying to create a temptable dynamically in tsql . I have a query which gives me some data (as a result of another dynamic query ) in a column. For example say years like 2011/2012 . This will be in a column. What i want is to pick value of each row and name it as a column name of type int. Later , i can use that temp table to dump data into it.

Any suggestions?


回答1:


Would you be able to use something like this?

DECLARE @Tab VARCHAR(MAX)
SET @Tab = 'CREATE TABLE #Whatever ('

SELECT @Tab = @Tab + QUOTENAME(ColumnName) + ' INT NULL
,'
FROM @This
SELECT @Tab = SUBSTRING(@Tab,1,LEN(@Tab)-1) + ')'
PRINT @Tab
-- EXEC (@Tab)

Two points: You might find that you will need to create the temp table without using dynamic sql, then adjust the select statement to alter the table; this is so that the table exists in the current context - if the create statement is in the dynamic, you may get an error.

I don't like using dynamic sql like this - if you could use a pivot later to return the columns, that might be a better option (I'm not sure whether it's possible in this case).



来源:https://stackoverflow.com/questions/36174738/dynamic-creation-of-table-in-tsql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!