【问题标题】:Is there a simpler method for getting the two digit year?有没有更简单的方法来获得两位数的年份?
【发布时间】:2022-06-27 23:04:33
【问题描述】:

我需要将两位数的年份附加到发票号(为简单起见,我使用的是测试变量)。以前我只需要附加月份和日期,但客户现在要求输入两位数的年份。

我的方法: REPLACE + SUBSTRING + STR + YEAR(可变日期时间)

REPLACE((SUBSTRING(STR (Year(@Date),4),3,2)), ' ', '0')

我的代码:

DECLARE @TestVariable AS VARCHAR(100),
@Date as datetime = GetDate()
SET @TestVariable = '1234' 
+ REPLACE(STR(MONTH(@Date), 2), ' ', '0') 
+ REPLACE(STR(DAY(@Date), 2), ' ', '0') 
+  REPLACE((SUBSTRING(STR (Year(@Date),4),3,2)), ' ', '0')

PRINT @TestVariable

【问题讨论】:

  • 因为 sargability 已经不在了,你可以使用FORMAT。像这样的东西。 SET @TestVariable = '1234' + FORMAT(getdate(), 'MMddyy')

标签: sql sql-server tsql datetime type-conversion


【解决方案1】:

使用 DATEPART(yy, @date)。请参阅文档,here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-01
    • 2020-01-21
    • 2011-10-26
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多