sqlserver 动态创建临时表的语句分享

因此计划先把数据转插入一个临时表,再对临时表的数据进行分析。

问题点是如何动态创建临时表。原先insus.net使用下面代码实现:


复制代码 代码如下:

declare @s nvarchar(max) = ‘

if object_id(”[dbo].[#tb]”) is not null

drop table [dbo].[#tb]

create table [dbo].[#tb]

(

[xxx] int,

[xxx] nvarchar(50),

‘+ [dbo].[column]() + ‘

)’

execute(@s)

上面代码中,有一个函数[dbo].[column]() 是取得一系列动态字段。

其实,上面的代码一点问题也没有,是能正确动态创建一个临时表,但是接下来代码,我们无法再使用这个临时表[dbo].[#tb] ,因为run第10行代码execute(@s)这动作之后,进程已经结束了。这样说法,动态创建出来的临时表,也没有什么意义了。

为了解决这个问题,insus.net想到了一个方法,算是能解决这个问题。既能动态创建,又能在创建之后,能继续使用这个临时表。

复制代码 代码如下:

if object_id(‘[dbo].[#tb]’) is not null

drop table [dbo].[#tb]

create table [dbo].[#tb]

(

[xxx] int,

[xxx] nvarchar(50)

)

declare @tb nvarchar(max) = ‘alter table [dbo].[#tb] add ‘ + [dbo].[column]()

execute(@tb)

只要细心看了一下,就是可以知道,可以先按正常创建这个临时表,再动态修改这个临时表的字段。这样做之后,程序run完第10行代码之后,就能再继续使用这个临时表,如:

select * from [dbo].[#tb]

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐