SQL刪除字段及判斷字段是否存在的方法


下面為您介紹使用SQL語句如何增加、刪除、修改字段,並判斷字段是否存在的詳細語句寫法,供您參考,希望對您有所幫助。

增加字段
alter table docdsp  add dspcode char(200)
刪除字段
ALTER TABLE table_NAME DROP COLUMN column_NAME
修改字段類型
ALTER TABLE table_name  ALTER COLUMN column_name new_data_type
改名
sp_rename
更改當前數據庫中用戶創建對象(如表、列或用戶定義數據類型)的名稱。
語法
sp_rename [ @objname = ] 'object_name' ,
    [ @newname = ] 'new_name'
    [ , [ @objtype = ] 'object_type' ]

--假設要處理的表名為: tb

--判斷要添加列的表中是否有主鍵
if exists(select 1 from sysobjects where parent_obj=object_id('tb') and xtype='PK')
begin
 print '表中已經有主鍵,列只能做為普通列添加'

--添加int類型的列,默認值為0
 alter table tb add 列名 int default 0
end
else
begin
 print '表中無主鍵,添加主鍵列'

--添加int類型的列,默認值為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

 

轉自http://database.51cto.com/art/201009/223550.htm


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM