T-SQL 判断字段是否存在的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. --添加int类型的列,默认值为0
  6. alter table tb add 列名 int default 0
  7. end
  8. else
  9. begin
  10. print '表中无主键,添加主键列'
  11. --添加int类型的列,默认值为0
  12. alter table tb add 列名 int primary key default 0
  13. end
  14. /**************************************************************************************/
  15. 判断table1中是否存在name字段
  16. if exists(select * from syscolumns where id=object_id('table1') and name='name') begin
  17. select * from people;
  18. end
  19. 判断table1中是否存在name字段且删除字段
  20. if exists(select * from syscolumns where id=object_id('table1') and name='name') begin
  21. select * from people;
  22. alter table table1 DROP COLUMN name
  23. end

转载于:https://www.cnblogs.com/jackljf/archive/2012/12/06/3589269.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值