Skip to content
Advertisement

Trying to assign the value of an SQL Query to a variable SET

I am trying to get date in format yyyymm and then use that date in some operation.

declare @currdate datetime
set @currdate = (SELECT CONVERT(nvarchar(6), GETDATE(), 112))

ERROR:

The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.

Or if I use below:

declare @currdate datetime
set @currdate = SELECT FORMAT(GetDate(),'yyyyMM')

I get same error as above.

So I want if today’s date is 17-05-2020, I want 202005 as output and i want to store that output in some variable.

Advertisement

Answer

You have declare the var as date then

Or you declare a varchar

    declare @currdate nvarchar(6)
    set @currdate = (SELECT CONVERT(nvarchar(6), GETDATE(), 112))

or as clearly precised by @MartinSmith

it is char(6). It is neither variable length nor requires any characters outside of ASCII digits

    declare @currdate char(6)
    set @currdate = (SELECT CONVERT(nvarchar(6), GETDATE(), 112))

or you use as date

declare @currdate datetime
set @currdate GETDATE(),
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement