有一种情况,我必须在现有表上删除主键,然后在其中插入一条记录。该表有一个名为 GUID 的列,如下所示
Create Table TEST_TABLE_VALUE (
TEST_TABLE_ID int Identity(1,1),
TEST_TABLE_VALUE int,
GUID uniqueidentifier Not Null Default newid(),
Primary Key (TEST_TABLE_ID, TEST_TABLE_VALUE)
)
使用以下代码删除约束
Declare @TableName nvarchar(100)
Declare @TableId int
Declare @ConstraintName varchar(120)
Declare @IndexName varchar(120)
Declare @Command varchar(256)
Set @TableName = 'TEST_TABLE_VALUE'
Select @TableId = id From sysobjects Where [type]='U' and [name]=@TableName
Declare ConstraintDropCursor Cursor Local Fast_Forward
For Select name from sysobjects where (type='K' Or type='D' or type='F' or type='C') and parent_obj = @TableId
For Read Only
Open ConstraintDropCursor
Fetch Next From ConstraintDropCursor Into @ConstraintName
While @@Fetch_Status != -1
Begin
Set @Command = 'Alter Table dbo.' + @TableName + ' Drop Constraint ' + @ConstraintName
exec(@Command)
Fetch Next From ConstraintDropCursor Into @ConstraintName
End
Close ConstraintDropCursor
DeAllocate ConstraintDropCursor
当我尝试将数据插入表中时删除约束后
Insert Into TEST_TABLE_VALUE (TEST_TABLE_VALUE) Values(1)
但出现以下错误:
Cannot insert the value NULL into column 'GUID', table 'CustApp1.dbo.TEST_TABLE_VALUE1'; column does not allow nulls. INSERT fails.
我该如何解决这个问题?