如何使用查询删除sql server中的空约束

我试图删除SQL Server 2008中不空的约束,而不会丢失数据。

ALTER TABLE YourTable ALTER COLUMN YourColumn columnType NULL 

删除约束not nullnull

ALTER TABLE 'test' CHANGE COLUMN 'testColumn' 'testColumn' datatype NULL;

只为后人:

我是这样声明我的列名:

 ALTER TABLE <table_name> ADD <column_name> <datatype> NOT NULL DEFAULT 0 

要以编程方式成功删除<column_name>,应该像这样声明列:

 ALTER TABLE <table_name> ADD <column_name> <data_type> NOT NULL CONSTRAINT <default_constraint_name> DEFAULT 0 

删除<column_name>:

  1. ALTER TABLE <table_name> DROP <default_constraint_name>
  2. ALTER TABLE <table_name> ALTER COLUMN <column_name> <data_type> NULL
  3. ALTER TABLE <table_name> DROP COLUMN <column_name>

在删除不空列之前,您应该删除任何约束

 DECLARE @ConstraintName nvarchar(200) SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS WHERE PARENT_OBJECT_ID = OBJECT_ID('<tableName>') AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns WHERE NAME = N'<columnToDelete>' AND object_id = OBJECT_ID(N'<columnToDelete>')) IF @ConstraintName IS NOT NULL EXEC('ALTER TABLE <tableNAme> DROP CONSTRAINT ' + @ConstraintName) IF EXISTS (SELECT * FROM syscolumns WHERE id=object_id('<TableName>') AND name='<columnToDelete>') EXEC('ALTER TABLE <tableName> DROP COLUMN <columnToDelete>') 

它适合我!