简体   繁体   中英

My “data default (getdate())”, it doesn't work

I'm trying to insert in my SQL Server table the current date.

My table includes 3 files:

CREATE TABLE [dbo].[MyTable] 
(
     [Id]   INT IDENTITY (1, 1) NOT NULL,
     [Name] NVARCHAR (50) NOT NULL,
     [Date] DATE 
         CONSTRAINT [DF_MyTable_Date] DEFAULT (getdate()) NOT NULL,

     CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED ([Id] ASC)
) 

When a new user wants to register in the system, he has only to insert his name.

In my table, the Id is generated automatically and the date too, but the date shows 01/01/0001 instead of the current day.

Where is the mistake?

if you create a datetime variable in C# like

var today_date = new DateTime();

and do a Console.WriteLine(today_date); u can see it print 0001-01-01

So this is default value of null..

Use DBNull.Value to insert a SQL NULL from C# and check the result

在此处输入图片说明

(Your_Date_Column) Make it Null / Not Null and give default value GetDate() but still it will not work. You have to create a trigger like this,

CREATE TRIGGER [dbo].[Trigger_Date] ON [dbo].[TableName] FOR INSERT AS BEGIN

Declare @Id int
set @Id = (select Id from inserted)

Update [dbo].[TableName]
Set Your_Date_Column = GetDate()
Where Id = @Id

END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM