注册 登录
编程论坛 SQL Server论坛

[求助]请教如何判断一个SQL表中是否存在某个列?

cobby 发布于 2007-08-29 09:40, 1959 次点击
如题。比如有表depart,已知里面有列id,name,但是不知道是否有列num,我如何用语句判断是否有这个列呢?返回值最好是一个逻辑值。谢谢了!
2 回复
#2
siy5132007-08-29 19:32

use master
go

if exists(select * from sysobjects where name='depart')
drop table depart
create table depart
(
dId int,
dName varchar(20)
--,dNum int --要有这个列的话去掉注释就OK了
)
go

if exists(select * from sysobjects where name='view_name')
drop view view_name
go
create view view_name
as
select top 100 percent name
from syscolumns
where id=object_id('depart')
order by colorder
go
--select * from view_name

declare @count int
select @count= count(*) from view_name where name='dnum'
--print @count
declare @result bit --用来存放最后结果0表示没有dnum列,1表示有

if(@count=0)
set @result=0
else
set @result=1

print '结果为 '+ convert(varchar(1),@result)


好久没搞过了
试一下
不知道是否符合你的需要

#3
cobby2007-08-30 14:56
谢谢,已经搞定了,不过我用的是
select name from syscolumns where id=(select id from sysobjects where xtype='u' and name='"+table_name+"')
好不容易问到的呵。谢谢帮忙哦
1