检查临时表是否存在

2025-03-25 07:49:49
推荐回答(1个)
回答1:

sql serverif object_id('tempdb..##TEMPTABLE1') isnotnulldroptable ##TEMPTABLE1 上面一种不检查类型,##TEMPTABLE1可能是view或procedure的名字,完整的检查如下 ifexists (select * from tempdb.dbo.sysobjects where id = object_id(N'tempdb..##TEMPTABLE1') and type='U') droptable ##TEMPTABLE1 处理临时表的注意事项使用中发现 select into 临时表 很麻烦,下面是使用中发现的一些注意事项(一下以mssqlserver为例):1,一般使用create table person (id int ,name varchar(20),birthday datetime) 读取数据到临时表中 select * into #tb_tmp from person where .... 使用临时表中的数据 select name from #tb_tmp where id = 1 使用之后不要忘记删除临时表(drop table #tb_tmp),否则下次使用时会报错如: 消息2714,级别 16,状态 6,第 1 行 There is already an object named '#tb_tmp' in the database.2,常见问题 select '' as col into #tb_tmp 会包如下错误: 消息2731,级别 16,状态 1,第 2 行 Column 'col' has invalid width: 0.解决以上问题有两种方法: 解决方案一,''->null select null as col into #tb_tmp 解决方案二,''->ltrim(' ') or ''->rtrim(' ') select rtrim(' ') as col into #tb_tmp 解决方案一引发的问题: 插入问题:只能插入int数字或数字类字符串(其中插入带小数的数字,小数部分会被自动去除) 如果插入数字以外的字符串,如:insert into #tb_tmp values('asdfsadf')会报如下错误: 消息245,级别 16,状态 1,第 3 行