0

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.

2 Answers 2

1

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(),
Sign up to request clarification or add additional context in comments.

4 Comments

Please read what i want ...i need 202005 as output for current date if today is 17-05-2020
then don't declare the var a date but as a nvarchar(6) . 202005 is nvarchar(6) NOT a date
it is char(6). It is neither variable length nor requires any characters outside of ASCII digits
@MartinSmith .. correct .. answer updated with your comment in evidence ..thanks
1

You don't specify if you want the result as a string or a number. As a number, it is easy:

select year(getdate()) * 100 + month(getdate())

This is trivially converted to a string:

select convert(varchar(6), year(getdate()) * 100 + month(getdate()))

However, your format() is just fine. The issue is the destination type -- it should be a string, not a date.

3 Comments

I need only to store this yyyymm into some place
@ShailajaGuptaKapoor . . . I don't understand your comment. Both of these generate a column of the format yyyymm, one as a number and the other as a string.
generation is fine, it was also about storing in some other variable, but thats been answered. Thank

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.