当前位置: 移动技术网 > IT编程>数据库>MSSQL > sql server创建临时表的两种写法和删除临时表

sql server创建临时表的两种写法和删除临时表

2017年12月12日  | 移动技术网IT编程  | 我要评论

宋茜 昌珉,如果我是陈奕迅,惟爱是卿

--创建、删除临时表

--第一种方式 
create table #tmp(name varchar(255),id int)

--第二种方式
select count(id) as storynum ,
sum(convert(numeric(10,2),case when isnumeric(code)=1 then code else 0 end)) as codenum,
sum((case when isnumeric(realcode)=1 then convert(numeric(10,2),realcode) else 0.0 end)) as realcodenum,
tdtname,cycle,jiracomponent,jirastatename,qualityvalue,storycodellt 
into #tmp from iknow_story_u2000v1r7c00 group by tdtname,cycle,jiracomponent,jirastatename,qualityvalue,storycodellt

--查询临时表
select * from #tmp

--删除临时表
if object_id('tempdb..#tmp') is not null
	begin
		drop table #tmp 
	end 

sql server临时表的正确删除方式

删除sql server临时表和一般表并不相同,下面将为您为别示例错误和正确的删除操作,供您参考,希望对您能够有所帮助。

临时表与一般的表不同,它是保存到tempdb表中。临时表的表名与你所建的表名也不一样,因为他要为不同人的相同操作创建不同的临时表。

1、错误的删除操作:

--错误的临时表删除操作,因为所在数据库不同
if exists (select * from sysobjects where object_id = object_id(n'[dbo].[#temptable]') and type in (n'u'))
 begin
 drop table [dbo].[temptable]
end
 --错误的临时表删除操作,因为临时表名已变
if exists (select * from tempdb.dbo.sysobjects where id = object_id(n'[#temptable]'))
begin
 drop table #temptable
end

2、正确的删除方式:

--正确的临时表删除操作
if object_id('tempdb..#temptable') is not null begin
 drop table #temptable
end

sql 判断临时表是否存在,删除临时表重建

if object_id('tempdb..#dl') is not null  
drop table #dl --如果有存在就删除临时表
create table #dl (neirong char(20),icount int, dlzonjine int, dlshu int, dlyin int) --重建临时表
insert into #dl select * from tab1 --把物理表的数据插到临时表

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网