当修改数据库的时候,如果需要修改一个not null栏位时,由于SQL SERVER自动生成的 Constraints 导致不能Alter
需要先Drop掉这个 Constraints 才可以进行。
关键问题在于 Constraints 是随机生成的,我们无法得到它的名称,不能直接drop。
该script就是用来解决这个问题的。
只要修改相应的值就好了
1Declare @name nvarchar(128)
2Declare @tableName nvarchar(128)
3Declare @columnName nvarchar(128)
4Declare @statement nvarchar(4000)
5Set @tableName = ''
6Set @columnName = ''
7Select @name = [name] From sysobjects Left Join sysconstraints on constid = sysobjects.id
8 Where xtype = 'D' And parent_obj = object_id(@tableName)
9 And col_name(parent_obj,colid) = @columnName
10
11if @name > ''
12 begin
13 set @statement = 'Alter Table ' + @tableName + ' Drop Constraint ' + @name
14 +';Alter Table '+ @tableName + '
15 Alter Column '+ @columnName + ' char(5) NOT NULL;'
16 --Select @statement
17 exec sp_executesql @statement
18 end
19GO
20
2Declare @tableName nvarchar(128)
3Declare @columnName nvarchar(128)
4Declare @statement nvarchar(4000)
5Set @tableName = ''
6Set @columnName = ''
7Select @name = [name] From sysobjects Left Join sysconstraints on constid = sysobjects.id
8 Where xtype = 'D' And parent_obj = object_id(@tableName)
9 And col_name(parent_obj,colid) = @columnName
10
11if @name > ''
12 begin
13 set @statement = 'Alter Table ' + @tableName + ' Drop Constraint ' + @name
14 +';Alter Table '+ @tableName + '
15 Alter Column '+ @columnName + ' char(5) NOT NULL;'
16 --Select @statement
17 exec sp_executesql @statement
18 end
19GO
20