首页 > 解决方案 > 使用 SQL Server 打印一个句子说一年中的哪一天

问题描述

我正在尝试使用 SQL SERVER 编写此代码:

“嗨!今天是……这是一年中的……天数。除夕是……天”。

我的代码运行没有问题,但我也无法打印。我究竟做错了什么?我还没有完成整个短语,因为我需要在进入最后一部分之前解决问题。

DECLARE
    @currentDate DateTime
        SET @currentDate = GETDATE();

DECLARE @dayofyear datetime
SET @dayofyear=DATEDIFF(day,STR(YEAR(@dayofyear),4)+'0101',@dayofyear)+1
-- SELECT Numbertoday = DATEDIFF(day,STR(YEAR(@dayofyear),4)+'0101',@dayofyear)+1

print('Hi! Today is '+ CONVERT(VARCHAR(10), @currentDate , 111) + '. ' + 'This is the day number '+ ' ' +  CONVERT (VARCHAR(10), @dayofyear) + of the year.')   

标签: sql-servertsqldate

解决方案


另一种方法是:

    declare @today varchar(11) = convert(varchar(11), getdate(), 1);

    declare @dayOfTheYear int = datepart(DAYOFYEAR, getdate());

    declare @untilNewYearsEve int = datepart(dayofyear, datefromparts(year(getdate()), 12, 31)) - @dayOfTheYear

   -- if you use print, you should see the result under the 'messages' tab not in the 'results' tab in SSMS
    print 'Hi! Today is '+ @today + '. ' + 'This is the day number '+ cast( @dayOfTheYear as varchar(3)) +  '. New year''s eve is in '+ 
    cast (@untilNewYearsEve as varchar(3)) + ' days.'

推荐阅读