判断字段是否存在的SQL语句写法

树叶云

下文为您介绍的SQL语句可以实现判断字段是否存在,并判断添加列的表中是否有主键,这些SQL语句比较有实用的价值,希望可以让您对SQL语句有更多的认识。

  1. --判断要添加列的表中是否有主键      
  2. if exists(select 1 from sysobjects where parent_obj=object_id('tb') and xtype='PK')      
  3. begin     
  4. print '表中已经有主键,列只能做为普通列添加'     
  5.      
  6. --添加int类型的列,默认值为0      
  7. alter table tb add 列名 int default 0      
  8. end     
  9. else     
  10. begin     
  11. print '表中无主键,添加主键列'     
  12.      
  13. --添加int类型的列,默认值为0      
  14. alter table tb add 列名 int primary key default 0      
  15. end     
  16. /**************************************************************************************/      
  17.      
  18. 判断table1中是否存在name字段      
  19. if exists(select * from syscolumns where id=object_id('table1') and name='name') begin     
  20. select * from people;      
  21. end     
  22.  
  23. 判断table1中是否存在name字段且删除字段   
  24. if exists(select * from syscolumns where id=object_id('table1') and name='name') begin     
  25. select * from people;     
  26. alter table table1 DROP COLUMN name   
  27. end  

 

 

 

 

【编辑推荐】

表添加字段的SQL语句写法

SQL Xml字段的修改方法

查询XML类型数据的SQL语句

SQL定义Xml字段

Sql Server表相关的语句

文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/229577.html<

(0)
运维的头像运维
上一篇2025-04-18 20:15
下一篇 2025-04-18 20:16

相关推荐

发表回复

您的邮箱地址不会被公开。必填项已用 * 标注