+ -
当前位置:首页 → 问答吧 → 怎么判断临时表里存在一个字段?

怎么判断临时表里存在一个字段?

时间:2011-11-29

来源:互联网

比如,生成的#temp临时表应该有字段f1,怎么判断这个f1字段是否在#temp临时表里有呢?因为我要从临时表做这样的查询:

SQL code

select
 (case 
   when [f1]='' then '1'
   when [f1]='A'  then '2'
 end) as f1 from #temp




但是如果f1不小心不存在的话,就要报错,怎么判断呢?

作者: chinazdq   发布时间: 2011-11-29

先判断一下 #temp是否存在
不存在就把创建临时表的语句执行一遍
存在就删除 然后执行创建表 
确保 #temp存在 f1它就存在 
再查询就OK了




作者: yhui1989love   发布时间: 2011-11-29

SQL code
if exists(select 1 from tempdb.dbo.syscolumns where ID=OBJECT_ID('Tempdb..#temp') and name='f1')
print '存在'
else 
print '不存在'

作者: roy_88   发布时间: 2011-11-29

引用 2 楼 roy_88 的回复:
SQL code
if exists(select 1 from tempdb.dbo.syscolumns where ID=OBJECT_ID('Tempdb..#temp') and name='f1')
print '存在'
else
print '不存在'

.

作者: fredrickhu   发布时间: 2011-11-29

+1
引用 2 楼 roy_88 的回复:
SQL code
if exists(select 1 from tempdb.dbo.syscolumns where ID=OBJECT_ID('Tempdb..#temp') and name='f1')
print '存在'
else
print '不存在'

作者: szstephenzhou   发布时间: 2011-11-29

SQL code

create table #temp1 (f1 char(1))
create table #temp2 (f2 char(1))

use tempdb

if col_length('#temp1','f1') is not null
 print 'exists'
else
 print 'not exists' 
 
--> exists

if col_length('#temp2','f1') is not null
 print 'exists'
else
 print 'not exists' 

--> not exists

作者: ap0405140   发布时间: 2011-11-29

SQL code

if object_id('tempdb..#t') is not null
   drop table #t
go
create table #t(f1 varchar(10))
go
if exists(select * from tempdb..syscolumns where id=object_id('tempdb..#t') and name='f1')
   print 'exists'
else
   print 'not exists'

作者: pengxuan   发布时间: 2011-11-29

if exists(select 1 from tempdb.dbo.syscolumns where ID=OBJECT_ID('Tempdb..#temp') and name='f1')
print '存在'
else 
print '不存在'

作者: clicsullivan   发布时间: 2011-11-29

热门下载

更多