I want to create a temporary table where the period is always the previous month in abbreviation. For example today the default value would be 'Sep'.
I have this code but it throws me errors after trying add other values to the table:
create table tmp_hfm
(
Entity_Code nvarchar(15),
HFM_Account nvarchar(15),
HFM_Segment nvarchar(15),
Period date default format(month(getdate()) - 1, 'mmmm')
)
The error I get:
Conversion failed when converting date and/or time from character string.
Can someone advise on this please?
Try this:
CREATE TABLE tmp_hfm (
Entity_Code NVARCHAR(15),
HFM_Account NVARCHAR(15),
HFM_Segment NVARCHAR(15),
Period CHAR(3) DEFAULT FORMAT(DATEADD(MONTH, -1, GETDATE()), 'MMM')
);
If you need to specify culture, you can add another parameter after 'MMM':
CREATE TABLE tmp_hfm (
Entity_Code NVARCHAR(15),
HFM_Account NVARCHAR(15),
HFM_Segment NVARCHAR(15),
Period CHAR(3) DEFAULT FORMAT(DATEADD(MONTH, -1, GETDATE()), 'MMM', 'en-us')
);
Here is an SQL Fiddle for you: link
I don't understand what you want to do. You have defined Period
as a date
column. FORMAT()
returns a string. They are not compatible.
Perhaps you want period
to be char(3)
, with a default of format(dateadd(month, -1, getdate()), 'MMM')
.
For "Sep", I would be inclined to use left(datename(month, dateadd(month, -1, getdate())), 3)
, unless you have a reason for preferring the internationalization functionality of format()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.