2017-07-08 10 views
-2

データベースを作成していましたが、日付値が挿入されていない場合は、現在の日付を受け入れるカラムが必要でした。コードは機能しましたが、日付を挿入しても機能しませんでした。Microsoft SQL Serverにdatetime値を挿入できません

私は

OrderDate datetime null check (OrderDate <= getdate()) default getdate() 

表を作成している間に、このテーブルを作成するために使用されるコードであるに沿ってcheck制約を使用してdefault

create table Transactions.OrderDetails 
(
    PurchaseOrderID int identity(1, 1) primary key 
    , EmployeeID int not null 
    , ItemID int not null 
    , OrderDate datetime null check (OrderDate <= getdate()) default getdate() 
    , ReceivingDate datetime null --check (ReceivingDate > OrderDate) 
    , QO int not null --check (QO > QR) 
    , QR int null check (QR > 0) 
    , UnitPrice money not null check (UnitPrice > 0) 
    , ShippingMethod char(6) not null 
    , OrderStatus varchar(50) not null 
) 
+0

まあ、それは残念だが、あなたは私たちを示していない限り、あなたのテーブルを宣言し、そしてどのようにあなたがそれに行を挿入しようとしましたか、それは私たちが言うことができるすべてです。 –

+0

テーブルを作成する際にCHECK制約とDEFAULTを使用しましたが、ここでOrderDate datetime NULL CHECK(OrderDate <= getdate())DEFAULT getdate()、 –

+0

私たちに教えてください。あなたのテーブルを作成してテーブルに挿入するためのものです。 –

答えて

2

not nullを作成し、デフォルトを追加datetimeデータ型の場合、getdate()またはgetutcdate()の制約。

create table Orders (
    id int 
    , OrderDate_notnull datetime not null default getdate() 
    , OrderDate_null datetime null default getdate() 
); 

/* nullable column with default not specified in insert uses default*/ 
insert into Orders (id) values (1); 

/* nullable column with default specified in insert remains null */ 
insert into Orders (id,OrderDate_null) values (2,null); 

/* non-nullable column specified with null value throws an error */ 
--insert into Orders (id,OrderDate_notnull) values (3,null); 

select * from Orders; 

rextesterデモ:http://rextester.com/CCNT4591

リターン:

+----+---------------------+---------------------+ 
| id | OrderDate_notnull | OrderDate_null | 
+----+---------------------+---------------------+ 
| 1 | 2017-07-08 18:10:50 | 2017-07-08 18:10:50 | 
| 2 | 2017-07-08 18:10:50 | NULL    | 
+----+---------------------+---------------------+ 
+0

それは完璧に働いて、そのことをお気遣いください –

+0

@OsagieEhimare助けて嬉しいです! – SqlZim

+0

@OsagieEhimare ..素敵で、答えがあなたの問題を解決したことを示す答えに印を付けてください。 – Khan

関連する問題