把存储过程SELECT INTO到临时表

摘要:
在开发过程中,很多时候要把结果集存放到临时表中,常用的方法有两种。Msg8164,Level16,State1,Proceduresp_get_composite_job_info,Line72AnINSERTEXECstatementcannotbenested.展开错误信息中的存储过程:1execsp_helptextsp_get_composite_job_info发现里面还有个INSERTINTO…EXEC的嵌套调用,SQLServer在语法上不支持。12INSERTINTO@xp_resultsEXECUTEmaster.dbo.xp_sqlagent_enum_jobs@can_see_all_running_jobs,@job_owner,@job_id可以用分布式查询来避免这个问题,这种写法在INSIDESQLServer2005中作者提到过。首先到打开服务器选项AdHocDistributedQueries123456execsp_configure'showadvancedoptions',1RECONFIGUREGOexecsp_configure'AdHocDistributedQueries',1RECONFIGUREGO通过OPENROWSET连接到本机,运行存储过程,取得结果集使用windows认证123select*into#JobInfo_S1fromopenrowsetselect*from#JobInfo_S1使用SQLServer认证123SELECT*INTO#JobInfo_S2FROMOPENROWSETSELECT*FROM#JobInfo_S2这样的写法,既免去了手动建表的麻烦,也可以避免insertexec无法嵌套的问题。12345678--dbcc不能直接运行SELECTa.*into#tFROMOPENROWSET('SQLOLEDB','12

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

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

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

1 select * into #temp from sysobjects

再次运行,则会报错提示:数据库中已存在名为'%1!' 的对象。www.it165.net

Msg 2714, Level16, State 6, Line 2
There is alreadyan object named '#temp' in the database.

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

1234 if OBJECT_ID('tempdb..#temp') is not null
drop table #temp
select * into #temp from sysobjects
select * from #temp

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

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

二. INSERT INTO

1. 使用insert into,需要先手动创建临时表
1.1 保存从select语句中返回的结果集
123 create table test_getdate(c1 datetime)
insert into test_getdate select GETDATE()
select * from test_getdate

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

123456789101112 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 保存从动态语句返回的结果集
123456789 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语句,都可以通过这种方式来保存结果集。

2. 不能嵌套使用insert exec语句
下面这个例子,尝试保存sp_help_job的结果集到临时表,发生错误:

123456789101112131415161718192021222324252627282930313233343536 create table #JobInfo
(
job_id uniqueidentifier,
originating_server nvarchar(128),
name nvarchar(128),
enabled tinyint,
description nvarchar(512),
start_step_id int,
category nvarchar(128),
owner nvarchar(128),
notify_level_eventlog int,
notify_level_email int,
notify_level_netsend int,
notify_level_page int ,
notify_email_operator nvarchar(128),
notify_netsend_operator nvarchar(128),
notify_page_operator nvarchar(128),
delete_level int,
date_created datetime,
date_modified datetime,
version_number int,
last_run_date int,
last_run_time int,
last_run_outcome int,
next_run_date int,
next_run_time int,
next_run_schedule_id int,
current_execution_status int,
current_execution_step nvarchar(128),
current_retry_attempt int,
has_step int,
has_schedule int,
has_target int,
type int
)
insert into #JobInfo exec msdb..sp_help_job

返回错误信息:INSERT EXEC 语句不能嵌套。

Msg 8164, Level16, State 1, Procedure sp_get_composite_job_info, Line 72
An INSERT EXEC statement cannot benested.

展开错误信息中的存储过程:

1 exec sp_helptext sp_get_composite_job_info

发现里面还有个INSERT INTO…EXEC的嵌套调用,SQL Server在语法上不支持。

12 INSERT INTO @xp_results
EXECUTE master.dbo.xp_sqlagent_enum_jobs @can_see_all_running_jobs, @job_owner, @job_id

可以用分布式查询来避免这个问题,这种写法在INSIDE SQL Server 2005中作者提到过。
(1) 首先到打开服务器选项Ad Hoc Distributed Queries
123456 exec sp_configure 'show advanced options',1
RECONFIGURE
GO
exec sp_configure 'Ad Hoc Distributed Queries',1
RECONFIGURE
GO

(2) 通过OPENROWSET连接到本机,运行存储过程,取得结果集
使用windows认证
123 select * into #JobInfo_S1
from openrowset('sqloledb', 'server=(local);trusted_connection=yes','exec msdb.dbo.sp_help_job')
select * from #JobInfo_S1

使用SQLServer认证
123 SELECT * INTO #JobInfo_S2
FROM OPENROWSET('SQLOLEDB','127.0.0.1';'sa';'sa_password','exec msdb.dbo.sp_help_job')
SELECT * FROM #JobInfo_S2

这样的写法,既免去了手动建表的麻烦,也可以避免insert exec 无法嵌套的问题。几乎所有SQL语句都可以使用。

12345678 --dbcc不能直接运行

SELECT a.* into #t
FROM OPENROWSET('SQLOLEDB','127.0.0.1';'sa';'sa_password',
'dbcc log(''master'',3)') AS a
--可以变通一下

SELECT a.* into #t
FROM OPENROWSET('SQLOLEDB','127.0.0.1';'sa';'sa_password',
'exec(''DBCC LOG(''''master'''',3)'')') AS a

免责声明:文章转载自《把存储过程SELECT INTO到临时表》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇openwrt下安装nohupJS生成指定范围内的随机数(支持随机小数)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

SQL Server(三)

一、数据库操作 create database 数据库名称 ——创建drop database 数据库名称 ——删除use 数据库名称 ——使用go 两条SQL语句之间分隔 二、表的操作 create table 表名( 列名 类型 其它,列名 id类型 其它 ) ——使用primary key ——主键identity——自增长列not null ——非...

python轻量级orm框架 peewee常用功能速查

peewee常用功能速查 peewee 简介 Peewee是一种简单而小的ORM。它有很少的(但富有表现力的)概念,使它易于学习和直观的使用。 常见orm数据库框架 Django ORM peewee SQLAlchemy Django ORM 优点:易用,学习曲线短和Django紧密集合,用Django时使用约定俗成的方法去操作数据库缺点:Quer...

python3 爬虫之爬取安居客二手房资讯(第一版)

#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Author;Tsukasa import requests from bs4 import BeautifulSoup import pandas import time url_all = [] url_in = input('输入你所需...

mysql 基本使用教程(源于网络)

3.1. 连接与断开服务器 3.2. 输入查询 3.3. 创建并使用数据库 3.3.1. 创建并选择数据库 3.3.2. 创建表 3.3.3. 将数据装入表中 3.3.4. 从表检索信息 3.4. 获得数据库和表的信息 3.5. 在批处理模式下使用mysql 3.6. 常用查询的例子 3.6.1. 列的最大值 3.6.2. 拥有某个列的最大值的行...

[开荒啦]ECS服务器初体验

服务商:阿里云 操作系统:Linux 64位 Ubantu 20.04 64位 目录 另设了一个用户 安装tmux并配置了一些vim和tmux的便捷操作 安装docker Xshell配置ssh免密登录 利用本地Dos窗口连接服务器 今天对我第一个服务器(毛坯)做了一些简单的布置: 另设了一个用户总是直接操作根用户不是很好,权限太大,一不小心把服务器...

sqlserver存储过程

1、  存储过程 1)  尽量将代码段放到TRY…CATCH…。 但凡使用C#写过代码的人,都知道C#中TRY…CATCH…的运行和出错跳转逻辑,而SQL Server2005中,其运行和出错跳转逻辑与在C#中是一致的。TRY…CATCH…是SQL Server2005中新增的,功能强大,且很好用。 2) 定义变量时,可以使用前缀的方式标识变量的类型。在S...