INSERT语句与约束冲突

时间:2013-12-05 12:09:29

标签: sql datetime timestamp constraints check-constraints

我想在我的表中创建一个日期约束(我使用sql server)。我想确保我的一个列中的日期晚于当前日期和时间(我知道这听起来很奇怪,但这是一项任务,所以我别无选择)。我试着这样做:

ALTER TABLE sales ADD CONSTRAINT d CHECK (Date >  CURRENT_TIMESTAMP);

但稍后在将DEFAULT插入日期列时,我收到以下错误:

The INSERT statement conflicted with the CHECK constraint "d". 
The conflict occurred in database "Newsagents", table "dbo.Sales", column 'Date'.

这是上表:

CREATE TABLE Sales (
ID INT IDENTITY(1,1) NOT NULL  ,
ClientID INT REFERENCES Client(ClientID),
ProductNumber CHAR(10)  REFERENCES Product(ProductNumber),
Quantity INT NOT NULL,
Price FLOAT NOT NULL ,
Date TIMESTAMP  NOT NULL,
PRIMARY KEY ( ID ) 

以及我如何将我的数据插入Sales列并获得约束冲突:

DECLARE @counter INT
DECLARE @quantity int
DECLARE @prodNum varchar(20)
SET @counter = 0 
WHILE @counter < 10  
BEGIN
SET @quantity = (select FLOOR(RAND()*100))
SET @prodNum = (select TOP 1 ProductNumber from Product Order by NEWID())

 insert into Sales (ClientID, ProductNumber, Quantity, Price, Date )
 values(
 (select TOP 1 ClientID from Client Order by NEWID()),
 (select @prodNum),
 (select @quantity),
 ((select @quantity)*(select TOP 1 Price from Product where ProductNumber = @prodNum)),
 DEFAULT
 )
 SET @counter = @counter + 1 
 END 

有不同的方法吗?或者我做错了什么?

1 个答案:

答案 0 :(得分:0)

ALTER TABLE sales ADD CONSTRAINT d CHECK (Date >  GETDATE());

将Date列更改为datetime

相关问题