2012-07-20 45 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 

允许空值。