01. 把存儲過程結果集SELECT INTO到臨時表

原文:01. 把存儲過程結果集SELECT INTO到臨時表

在開發過程中,很多時候要把結果集存放到臨時表中,常用的方法有兩種。

一. 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 #tempselect * 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_helpuserselect * 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語句,都可以通過這種方式來保存結果集。

?

2. 不能嵌套使用insert exec語句

2.1 下面這個例子,嘗試保存sp_help_job的結果集到臨時表,發生錯誤

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, Level 16, State 1, Procedure sp_get_composite_job_info, Line 72
An INSERT EXEC statement cannot be nested.

展開錯誤信息中的存儲過程:

exec sp_helptext sp_get_composite_job_info

?

發現里面還有個INSERT INTO…EXEC的嵌套調用,SQL Server在語法上不支持。

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

?

?

2.2 可以用分布式查詢來避免這個問題,這種寫法在INSIDE SQL Server 2005中作者提到過
(1) 首先到打開服務器選項Ad Hoc Distributed Queries

exec sp_configure 'show advanced options',1
RECONFIGURE
GO
exec sp_configure 'Ad Hoc Distributed Queries',1
RECONFIGURE
GO

?

(2) 通過OPENROWSET連接到本機,運行存儲過程,取得結果集
使用windows認證

select * into #JobInfo_S1
from openrowset('sqloledb', 'server=(local);trusted_connection=yes','exec msdb.dbo.sp_help_job')select * from #JobInfo_S1

?

使用SQL Server認證

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語句都可以使用。

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

?


本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/278244.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/278244.shtml
英文地址,請注明出處:http://en.pswp.cn/news/278244.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

day5學python 基礎+裝飾器內容

基礎裝飾器內容 遞歸特性# 1.必須有一個明確的結束條件# 2.每次進入更深一層遞歸時,問題規模相比上次遞歸應有所減少# 3.遞歸效率不高 def run(n):print(n)if int(n/2)>0:return run(n / 2)print("-->",n) run(10) 局部變量與全局變量知識 1.全局變…

如何在Windows 10上跳過回收站以刪除文件

Windows 10 normally sends files you delete to the Recycle Bin. They’ll be kept until you empty it—or, in some cases, until Windows 10 automatically empties your Recycle Bin. Here’s how to skip the Recycle Bin and delete files immediately. Windows 10通常…

OSChina 周日亂彈 —— 我叫張一條

2019獨角獸企業重金招聘Python工程師標準>>> Osc亂彈歌單(2018)請戳(這里) 【今日歌曲】 萊布妮子 :分享Lube的單曲《Skoro dembel》 《Skoro dembel》- Lube 手機黨少年們想聽歌,請使勁兒戳&am…

面向對象初識

一. 面向對象初識 1.1 回顧面向過程編程vs函數式編程 # 面向過程編程 測量對象的元素個個數。 s1 fjdsklafsjda count 0 for i in s1:count 1l1 [1,2,3,4] count 0 for i in l1:count 1 面向過程編程def func(s):count 0for i in s:count 1return count …

iOS逆向:在任意app上開啟malloc stack追蹤內存來源

lldb有一個內存調試工具malloc stack,開啟以后就可以查看某個內存地址的malloc和free記錄,追蹤對象是在哪里創建的。 這個工具可以打印出對象創建的堆棧,而在逆向時,也經常需要追蹤某些方法的調用棧,如果可以隨時打印出…

【CH4302】Interval GCD

思路:線段樹維護a的差分數組的gcd, 因為$gcd(a_1,a_2,a_3,...,a_n)gcd(a_1,a_2-a_1,a_3-a_2,...,a_n-a_{n-1})$。 原區間修改可以轉化為差分數組上的兩次單點修改。 因為實際計算時還需要原數,所以用樹狀數組維護b的增減量。 詢問時&#xff…

Vue 的路由實現 Hash模式 和 History模式

Hash 模式: Hash 模式的工作原理是onhashchange事件,Window對象可以監聽這個事件... 可以通過改變路徑的哈希值,來實現歷史記錄的保存,發生變化的hash 都會被瀏覽器給保存下來,所以下次盡管瀏覽器沒有請求服務器,但是還…

我的第一次——網站備案

暫無內容 轉載于:https://my.oschina.net/vright/blog/1784979

使用LiveClick升級您的實時書簽

If you like to subscribe to feeds using Firefox’s Live Bookmarks feature, the LiveClick extension gives you so many upgrades that I can only cover the highlights of how great it is. 如果您想使用Firefox的“實時書簽”功能訂閱供稿,則LiveClick擴展程…

操作系統的概論梳理

轉載于:https://www.cnblogs.com/hclhechunlu/p/10477470.html

win7下如何顯示緬文和使用緬文輸入法?

windows 7 操作系統默認不支持緬文,所以緬文在win7上不能顯示,當然也沒有提供緬文輸入法。 一、顯示緬文 windows系統下顯示緬文字母只需要安裝緬文字體就可以了。目前常見的緬文字體就是Zawgyi-One,Zawgyi-One是一種廣泛使用的緬文字體。Zaw…

airpods2使用_如何使用AirPods和AirPods Pro:完整指南

airpods2使用Burdun Iliya/ShutterstockBurdun Iliya /快門Just bought yourself or received a new pair of AirPods or AirPods Pro? Welcome to the truly wireless earphones life. Setting up AirPods is quite straightforward, but here’s how to customize and get t…

LANG

修改 /etc/sysconfig/i18n 文件 locale 查看字符集 轉載于:https://www.cnblogs.com/todayORtomorrow/p/10479594.html

如何在iPhone上共享視頻之前從視頻中刪除音頻

Sometimes, you’d like to share a video with others, but the accompanying audio track is distracting or perhaps introduces privacy concerns. Luckily, there’s a quick way to silence a video using Photos on iPhone and iPad. Here’s how. 有時,您想…

入門第十一課 Python語句的嵌套

1、說個小故事:話說一個人買到一個治療瘙癢的偏方,在拆開無數層的包裝后,得到的只是一張寫著“撓撓”的小紙條兒。 嵌套,類似于在一個語句中,嵌套另一個語句。舉個栗子-_-!! 我們要計算從1到100之間,所有的…

【TensorFlow篇】--Tensorflow框架實現SoftMax模型識別手寫數字集

一、前述 本文講述用Tensorflow框架實現SoftMax模型識別手寫數字集,來實現多分類。 同時對模型的保存和恢復做下示例。 二、具體原理 代碼一:實現代碼 #!/usr/bin/python # -*- coding: UTF-8 -*- # 文件名: 12_Softmax_regression.pyfrom tensorflow.ex…

web頁面鎖屏初級嘗試

因為工作需要&#xff0c;所以在網上找了一些素材來弄這個功能。在我找到的素材中&#xff0c;大多都是不完善的。雖然我的也不是很完善&#xff0c;但是怎么說呢。要求不是很高的話。可以直接拿來用的【需要引用jQuery】。廢話不多說直接上代碼 這部分是js代碼 1 <script&g…

Java 并發工具箱之concurrent包

概述 java.util.concurrent 包是專為 Java并發編程而設計的包。包下的所有類可以分為如下幾大類&#xff1a; locks部分&#xff1a;顯式鎖(互斥鎖和速寫鎖)相關&#xff1b;atomic部分&#xff1a;原子變量類相關&#xff0c;是構建非阻塞算法的基礎&#xff1b;executor部分&…

如何提高gps精度_如何在鍛煉應用程序中提高GPS跟蹤精度

如何提高gps精度l i g h t p o e t/Shutterstocklightpoet /快門Tracking your runs, bike rides, and other workouts is fun because you can see how much you’re improving (or, in my case, dismally failing to improve). For it to be effective, though, you have to …

centos proftp_在CentOS上禁用ProFTP

centos proftpI realize this is probably only relevant to about 3 of the readers, but I’m posting this so I don’t forget how to do it myself! In my efforts to ban the completely insecure FTP protocol from my life entirely, I’ve decided to disable the FTP…