在tsql中动态创建表 [英] Dynamic creation of table in tsql

查看:366
本文介绍了在tsql中动态创建表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在tsql中动态创建一个临时表。我有一个查询,该查询在某列中提供了一些数据(作为另一个动态查询的结果)。例如说 2011/2012 之类的年份。这将在列中。我想要的是选择每一行的值并将其命名为int类型的列名称。
之后,我可以使用该临时表将数据转储到其中。

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.

有任何建议吗?

推荐答案

您可以使用这样的东西吗?

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)

两点:$ b​​ $ b您可能会发现需要在不使用动态SQL的情况下创建临时表。 ,然后调整选择语句以更改表;这样一来,该表就存在于当前上下文中-如果create语句处于动态状态,则可能会出错。

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.

我不喜欢使用动态sql这样-如果以后可以使用数据透视表返回列,那可能是一个更好的选择(我不确定在这种情况下是否可能)。

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).

这篇关于在tsql中动态创建表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆