结果集存放到临时表

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

      1.INSERT INTO SELECT语句

      语句形式为:Insert into Table2(field1,field2,...) select value1,value2,... from Table1

      要求目标表Table2必须存在,由于目标表Table2已经存在,所以我们除了插入源表Table1的字段外,还可以插入常量。

       2.SELECT INTO FROM语句

      语句形式为:SELECT vale1, value2 into Table2 from Table1

      要求目标表Table2不存在,因为在插入时会自动创建表Table2,并将Table1中指定字段数据复制到Table2中

  批量删除

delete from table where id in (xxxxxxxx) 或者delete from table where id in ( select id from table where enabled = 0)

    INNER JOIN 连接三个数据表的用法:

    SELECT (表?).字段,(表?).字段 。。。  FROM (表1 INNER JOIN 表2 ON 表1.字段号=表2.字段号) INNER JOIN 表3 ON 表1.字段号=表3.字段号

如何使用EXEC里面创建的临时表
当我这样创建临时表的时候可以使用:
select * into #tmp from TableA;
select * from #tmp;

但是这样创建临时表却不可以使用:
EXEC ('select * into #tmp from TableA');
select * into #tmp from TableA;
------解决方案--------------------
把SELECT..INTO 也写到EXEC里面去。 
------解决方案--------------------
如果后边还有用到临时表处理的东西,也写到exec中去。 

------解决方案--------------------
EXEC ('select * into #tmp from TableA;select * from #tmp')




  一. SELECT INTO
 
  1. 使用select into会自动生成临时表,不需要事先创建
 
  select * into #temp from sysobjects
 
  01. 把存储过程结果集SELECT INTO到临时表
 
  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语句,都可以通过这种方式来保存结果集。
 
  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
 
 
 

1、判断数据表是否存在

  方法一:

use yourdb;
go

if object_id(N'tablename',N'U') is not null
print '存在'
else 
print '不存在'


例如:
use fireweb;
go

if object_id(N'TEMP_TBL',N'U') is not null
print '存在'
else 
print '不存在'

方法二:

USE [实例名] 
GO

IF EXISTS  (SELECT  * FROM dbo.SysObjects WHERE ID = object_id(N'[表名]') AND OBJECTPROPERTY(ID, 'IsTable') = 1) 
PRINT '存在' 
ELSE 
PRINT'不存在'


例如:
use fireweb;
go

IF EXISTS  (SELECT  * FROM dbo.SysObjects WHERE ID = object_id(N'TEMP_TBL') AND OBJECTPROPERTY(ID, 'IsTable') = 1) 
PRINT '存在' 
ELSE 
PRINT'不存在'

2、临时表是否存在:

方法一:
use fireweb;
go

if exists(select * from tempdb..sysobjects where id=object_id('tempdb..##TEMP_TBL'))
PRINT '存在' 
ELSE 
PRINT'不存在'


方法二:
use fireweb;
go

if exists (select * from tempdb.dbo.sysobjects where id = object_id(N'tempdb..#TEMP_TBL') and type='U')
PRINT '存在' 
ELSE 
PRINT'不存在'

原文地址:https://www.cnblogs.com/gaobw/p/5634775.html