码迷,mamicode.com
首页 > 其他好文 > 详细

把存储过程结果集SELECT INTO到临时表

时间:2017-10-31 11:11:11      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:生成   ase   obj   sql   sel   select   temp   log   rac   

http://www.cnblogs.com/soundcode/p/3544586.html

开发过程中,很多时候要把结果集存放到临时表中,常用的方法有两种。

一. SELECT INTO 
1. 使用select into会自动生成临时表,不需要事先创建

select * into #temp from sysobjects
select * from #temp

 

2. 如果当前会话中,已存在同名的临时表

select * into #temp from sysobjects

 

再次运行,则会报错提示:数据库中已存在名为 ‘%1!‘ 的对象。
Msg 2714, Level 16, State 6, Line 2
There is already an object named ‘#temp‘ in the database.

在使用select into前,可以先做一下判断:

if OBJECT_ID(‘tempdb..#temp‘) is not null
drop table #temp

select * into #temp from sysobjects 
select * from #temp

 

3. 利用select into生成一个空表
如果要生成一个空的表结构,不包含任何数据,可以给定一个恒不等式如下:

select * into #temp from sysobjects where 1=2
select * from #temp

 

 

二. INSERT INTO
1. 使用insert into,需要先手动创建临时表

1.1 保存从select语句中返回的结果集

create table test_getdate(c1 datetime)
insert into test_getdate select GETDATE()
select * from test_getdate

 

1.2 保存从存储过程返回的结果集

技术分享
技术分享
create table #helpuser
(
UserName nvarchar(128),
RoleName nvarchar(128),
LoginName nvarchar(128),
DefDBName nvarchar(128),
DefSchemaName nvarchar(128),
UserID smallint,
SID smallint
)

insert into #helpuser exec sp_helpuser

select * from #helpuser
技术分享
技术分享

 

1.3 保存从动态语句返回的结果集

技术分享
技术分享
create table test_dbcc
(
TraceFlag varchar(100),
Status tinyint,
Global tinyint,
Session tinyint
)

insert into test_dbcc exec(‘DBCC TRACESTATUS‘)

select * from test_dbcc
技术分享
技术分享

 

对于动态SQL,或者类似DBCC这种非常规的SQL语句,都可以通过这种方式来保存结果集。

把存储过程结果集SELECT INTO到临时表

标签:生成   ase   obj   sql   sel   select   temp   log   rac   

原文地址:http://www.cnblogs.com/xyao1/p/7760072.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!