SYSDATETIME Date and Time Function¶
The SYSDATETIME date function, introduced in SQL Server 2008, returns a DATETIME2
value that contains the date and time of the computer on which the instance of SQL Server is running. The SYSDATETIME date function have more fractional seconds precision than the GETDATE date function. The syntax of the SYSDATETIME date function is as follows:
SYSDATETIME()
The SYSDATETIME date function is a non-deterministic function and view and expressions that reference this column cannot be indexed.
Sample Uses of the SYSDATETIME Date and Time Function¶
Here are a few uses of the SYSDATETIME date function:
Usage #1 : Log the Date and Time When a Row is Inserted in a Table¶
CREATE TABLE [dbo].[Transactions] (
[TransactionID] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[AccountNumber] VARCHAR(10),
[Amount] MONEY,
[TransactionDate] DATETIME DEFAULT ( SYSDATETIME() )
)
INSERT INTO [dbo].[Transactions] ( [AccountNumber], [Amount] )
VALUES ( '123-456-78', 1000.00 )
Usage #2 : Generate a Random Number¶
SELECT DATEPART(NS, SYSDATETIME()) / 100 AS [Random Number]
Usage #3 : Generate a Random Number Within a Range¶
DECLARE @MinValue INT
DECLARE @MaxValue INT
SET @MinValue = 51
SET @MaxValue = 100
SELECT (DATEPART(MS, SYSDATETIME()) % ( @MaxValue - @MinValue + 1)) + @MinValue AS [Random Number]
Usage #4 : Generate an Account Number, Reference Number or Tracking Number¶
-- Assuming [dbo].[Tracking] Table Contains All Existing Tracking Numbers
DECLARE @NewNumber DECIMAL(10, 0)
SELECT @NewNumber = MAX([TrackingNumber]) + 1
FROM [dbo].[Tracking]
WHERE [TrackingNumber] > YEAR(SYSDATETIME()) * 1000000 +
MONTH(SYSDATETIME()) * 10000 +
DAY(SYSDATETIME()) * 100
IF @NewNumber IS NULL
SET @NewNumber = YEAR(SYSDATETIME()) * 1000000 +
MONTH(SYSDATETIME()) * 10000 +
DAY(SYSDATETIME()) * 100 + 1
Usage #5 : Use as a Seed in the RAND Function¶
SELECT RAND(DATEPART(NS, SYSDATETIME()))
Usage #6 : Return a Random Number of Records¶
SELECT TOP (DATEPART(MS, SYSDATETIME())) *
FROM [master].[dbo].[spt_values]
ORDER BY NEWID()