如何同时判断表是否存在以及字段是否存在

niuzhouhai 2015-10-13 10:46:29
我想要删除某个字段,sql语句如下
IF EXISTS(select ObjectProperty(Object_ID( 'students'),'IsUserTable')) ALTER TABLE students DROP COLUMN status

但这个语句只能判断表是否存在,并未判断表下面的字段是否存在.结果导致我在执行批量语句的时候总是中断.如何在以上语句中在加入字段是否存在的判断呢?
...全文
145 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
niuzhouhai 2015-10-13
  • 打赏
  • 举报
回复
引用 4 楼 yangb0803 的回复:

IF (EXISTS(select ObjectProperty(Object_ID( 'students'),'IsUserTable'))
and (EXISTS(select case col_length('students','[status]') when null then 0 else 1 end)))
ALTER TABLE students DROP COLUMN [status]


表中是否存在列的判断有误,2楼那个我试过了可以用
niuzhouhai 2015-10-13
  • 打赏
  • 举报
回复
引用 2 楼 yupeigu 的回复:
IF EXISTS(select * from sys.tables where name ='students') and 
exists(select * from sys.columns where object_id = object_id('students') and name = 'status')
ALTER TABLE students DROP COLUMN status


试过可以用,谢谢,我原来不知道 两个EXISTS之间可以用and连起来
道玄希言 2015-10-13
  • 打赏
  • 举报
回复

IF (EXISTS(select ObjectProperty(Object_ID( 'students'),'IsUserTable'))
and (EXISTS(select case col_length('students','[status]') when null then 0 else 1 end)))
ALTER TABLE students DROP COLUMN [status]
  • 打赏
  • 举报
回复
IF EXISTS(select * from sys.tables where name ='students') and 
exists(select * from sys.columns where object_id = object_id('students') and name = 'status')
ALTER TABLE students DROP COLUMN status
zbdzjx 2015-10-13
  • 打赏
  • 举报
回复
SELECT * FROM SYS.all_columns 
where OBJECT_ID =(SELECT object_id FROM SYS.all_objects WHERE name='a000')
and name='id'


其中的a000是表名,id是列名。
道玄希言 2015-10-13
  • 打赏
  • 举报
回复
好像有个 col_length 函数。

select case col_length('students','status') when null then 0 else 1 end

22,207

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧