2012-07-20 39 views
0

有一種情況是,我必須在現有表上放置主鍵,然後向其中插入一條記錄。該表具有一個稱爲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. 

我該如何解決這個問題?

+1

一般認爲你應該放棄約束是一個線索,你做錯了什麼。這些約束是有原因的。 – HLGEM 2012-07-20 20:40:21

+0

@HLGEM,我放棄限制只是重新添加他們的專有名稱。在上述情況下,我忘了添加GUID默認約束。 – MNVR 2012-07-20 20:49:55

回答

3

您已經刪除了GUID列的默認值,並且它不是可以爲空的列。因此它導致了問題。如果你想插入大量的數據,並不想限制可能的性能原因。然後至少不要刪除不可空列的默認值。

0

好吧,如果你,如果你想繼續沿着這條道路下降你最終

Create Table TEST_TABLE_VALUE ( 
     TEST_TABLE_ID int Identity(1,1), 
     TEST_TABLE_VALUE int,       
     GUID uniqueidentifier Not Null, 
     Primary Key (TEST_TABLE_ID, TEST_TABLE_VALUE) 
) 

所以默認約束你要麼必須爲GUID列

,或者也做

提供一個值
ALTER TABLE TEST_TABLE_VALUE ALTER COLUMN GUID uniqueidentifier NULL 

允許空值。