有一種情況是,我必須在現有表上放置主鍵,然後向其中插入一條記錄。該表具有一個稱爲GUID列作爲使用以下代碼在使用t-sql刪除表約束之後發佈newid()
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][email protected]
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)
滴下約束後示於下
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)
)
掉落的約束但得到了以下錯誤:
Cannot insert the value NULL into column 'GUID', table 'CustApp1.dbo.TEST_TABLE_VALUE1'; column does not allow nulls. INSERT fails.
我該如何解決這個問題?
一般認爲你應該放棄約束是一個線索,你做錯了什麼。這些約束是有原因的。 – HLGEM 2012-07-20 20:40:21
@HLGEM,我放棄限制只是重新添加他們的專有名稱。在上述情況下,我忘了添加GUID默認約束。 – MNVR 2012-07-20 20:49:55