1.最近項目用到sql server ,有這樣一個場景,刪除一個含有默認值的字段,對於mysql來講直接drop就能夠了,但對於sql server來講,須要先刪除約束條件再刪除字段;mysql
加入給user 表新增一個默認值爲man的sex字段sql
ALTER TABLE dbo.user add sex nvarchar(10) default 'man';
而後刪除字段,此時會報錯,此時就要先刪除約束再刪除字段了。code
declare @tablename varchar(100), @columnname varchar(100), @tab varchar(100) set @tablename = 'user' --表名(不要加多餘的東西) set @columnname= 'sex' --字段名稱 declare @defname varchar(100) --約束名稱 declare @cmd varchar(100) --構造的SQL語句 select @defname = name from sysobjects so join sysconstraints sc on so.id = sc.constid where object_name(so.parent_obj) = @tablename and so.xtype = 'd' and sc.colid =(select colid from syscolumns where id = object_id(@tablename) and name = @columnname) select @cmd= 'alter table '+ @tablename+ ' drop constraint '+ @defname if @cmd is null print ' no default constraint to drop' exec (@cmd) #以上爲刪除約束條件的語句 ALTER TABLE dbo.user DROP COLUMN sex; #刪除字段
2. 還有建立視圖時,後綴加goserver
DROP VIEW if exists [test]; go create view test as select * from user; go