SQL – How To get The Current Date Using GetDate()

The getDate() function is used to generate the current date.

print getDate()

This can be used with variables to create the date format required. The following code will set the string equivalent of the date format DD/MM/YY to the variable @date.

declare @date as nvarchar(50)
declare @day as nvarchar(50)
declare @month as nvarchar(50)
declare @year as nvarchar(50)
declare @zeroday as nvarchar(50)
declare @zeromonth as nvarchar(50)

— SET THE DATE
set @date         = cast(getDate() as char)
set @day          = day(@date)
if @day < 10
      set @zeroday = 0
else
      set @zeroday = ”
set @month  = month(@date)
if @month < 10
      set @zeromonth = 0
else
      set @zeromonth = ”
set @year         = year(@date)
set @date   = @zeroday + @day + ‘/’ + @zeromonth + @month + ‘/’ + right(@year,2)

print @date

To get yesterday’s date replace this line

set @date         = cast(getDate() as char)

with:

set @date         = cast(getDate() – 1 as char)

To get the date 1 week ago, use:

set @date         = cast(getDate() – 7  as char)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s