[英]Setting the previous month as a default value in 'mmm' format in SQL Server?
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'.
例如,今天的默认值为“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':如果需要指定文化,可以在'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')
);
I don't understand what you want to do.我不明白你想做什么。 You have defined
Period
as a date
column.您已将
Period
定义为date
列。 FORMAT()
returns a string. FORMAT()
返回一个字符串。 They are not compatible.它们不兼容。
Perhaps you want period
to be char(3)
, with a default of format(dateadd(month, -1, getdate()), 'MMM')
.也许您希望
period
为char(3)
,默认为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()
.对于“Sep”,我倾向于使用
left(datename(month, dateadd(month, -1, getdate())), 3)
,除非您有理由更喜欢format()
的国际化功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.