判斷字段是否存在的SQL語(yǔ)句寫(xiě)法
作者:佚名
如果需要判斷添加列的表中是否有主鍵,或者是判斷字段是否存在,應(yīng)該怎么做呢?下面就為您介紹實(shí)現(xiàn)該功能的SQL語(yǔ)句寫(xiě)法,供您參考學(xué)習(xí)。
下文為您介紹的SQL語(yǔ)句可以實(shí)現(xiàn)判斷字段是否存在,并判斷添加列的表中是否有主鍵,這些SQL語(yǔ)句比較有實(shí)用的價(jià)值,希望可以讓您對(duì)SQL語(yǔ)句有更多的認(rèn)識(shí)。
- --判斷要添加列的表中是否有主鍵
- if exists(select 1 from sysobjects where parent_obj=object_id('tb') and xtype='PK')
- begin
- print '表中已經(jīng)有主鍵,列只能做為普通列添加'
- --添加int類型的列,默認(rèn)值為0
- alter table tb add 列名 int default 0
- end
- else
- begin
- print '表中無(wú)主鍵,添加主鍵列'
- --添加int類型的列,默認(rèn)值為0
- alter table tb add 列名 int primary key default 0
- end
- /**************************************************************************************/
- 判斷table1中是否存在name字段
- if exists(select * from syscolumns where id=object_id('table1') and name='name') begin
- select * from people;
- end
- 判斷table1中是否存在name字段且刪除字段
- if exists(select * from syscolumns where id=object_id('table1') and name='name') begin
- select * from people;
- alter table table1 DROP COLUMN name
- end
【編輯推薦】
責(zé)任編輯:段燃
來(lái)源:
互聯(lián)網(wǎng)