I want to create a SQL Script to clean datetime2 field and set it up to datetime2 begin
'1-1-0001 12:00:00'. How to set
'1-1-0001 12:00:00' instead of using convert function ?
UPDATE XYZTable SET ReferralDate = CONVERT(datetime2, '1/1/0001 09:00')
Well, a couple things.
GETDATE() returns a datetime value, which has a valid range of January 1, 1753, through December 31, 9999. 1753 is when the civilized (or is it civilised?) world switched to the Gregorian calendar from the Julian one. So you won’t be able to have it return the date you’re after; it’s out of range.
You can use SYSDATETIME() to get you there, because it returns a datetime(2) value. However, it won’t necessarily be any cleaner code-wise than using CONVERT on that string. You’d have to throw some weird date math at it, like
SELECT DATEADD(MINUTE, DATEDIFF(MINUTE, SYSDATETIME(), '00010101 12:00:00.0000000'), SYSDATETIME()).
If this is just going to be a canary value, you’re better off setting it as the column default value.
ReferralDate DATETIME(2) DEFAULT '00010101 12:00:00.0000000'
If you need to update, it might be a little simpler to set it in a variable and then update using the variable.
CREATE TABLE #crap (Id INT IDENTITY(1,1), Dt DATETIME2(7)) GO INSERT #crap ( Dt ) VALUES ( NULL) GO 1000 SELECT * FROM #crap AS c DECLARE @dt DATETIME2(7) = '00010101 12:00:00.0000000' SELECT @dt UPDATE c SET c.Dt = @dt FROM #crap AS c WHERE c.Dt IS NULL SELECT * FROM #crap AS c