Link to home
Start Free TrialLog in
Avatar of damixa
damixaFlag for Denmark

asked on

Setting default value when creating table

I am trying to create a table and set a default value for one of the field to 'yyyymm'
the code I am using is

qry_mmyy varchar(6) default (CONVERT(VARCHAR(4),YEAR(getdate()) + CONVERT(VARCHAR(2),MONTH(getdate())))),

Open in new window


I am getting 2017 still though instead of 201502

any ideas would be welcome

thanks
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

-- This is the varchar
SELECT CONVERT(VARCHAR(4),YEAR(getdate())) + RIGHT('0' + CONVERT(VARCHAR(2),MONTH(getdate())),2)

The use of RIGHT('0'.. is required because February will evaluate to 2, and not 02, so to correct this add a zero to the left side and take the right-most two characters.

-- This is an int, assuming you'll want to do math on this value then any numeric is better
SELECT (CONVERT(VARCHAR(4),YEAR(getdate())) * 100) + CONVERT(VARCHAR(2),MONTH(getdate()))
ASKER CERTIFIED SOLUTION
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
qry_mmyy varchar(6) default CONVERT(varchar(6), getdate(), 112)
Avatar of damixa

ASKER

Thanks
Just to clarify for sure:
I assume you mean "computed column" rather than "calculated column"?