简体   繁体   English

声明一个将 Date 数据类型转换为 Integer 的变量

[英]Declare a variable which converts Date data type to Integer

In SQL Server, the following code gives me the date of Sunday last week from whatever date it is today:在 SQL 服务器中,以下代码为我提供了从今天开始的上周星期日的日期:

DECLARE @dt date = GETDATE();
SELECT dateadd(week,datediff(week,6,@dt),6);

I need to declare a variable from the date given and make that variable an integer.我需要从给定的日期声明一个变量,并将该变量设为 integer。 I have tried things like:我试过这样的事情:

DECLARE @last_sunday INT;
SELECT dateadd(week,datediff(week,6,@dt),6) INTO @last_sunday FROM xxx;

But the problem is that I don't understand which table I should write after FROM .但问题是我不明白我应该在FROM之后写哪个表。 In my interpretation the line:在我的解释中,这行:

dateadd(week,datediff(week,6,@dt),6)

is some sort of calculation rather than collecting a value from a data table.是某种计算,而不是从数据表中收集值。 How can I make last Sunday's date into a variable that is an integer?如何将上周日的日期转换为 integer 的变量?

You need to do something like this:你需要做这样的事情:

Step 1步骤1

DECLARE @date DATE = dateadd(week,datediff(week,6,GETDATE()),6)

Step 2第2步

DECLARE @dateInt AS INT = REPLACE(@date, '-', '')

In the first step, you are getting the correct date value in a date data type.在第一步中,您将获得日期数据类型中的正确日期值。 Given that the date has the hyphens, you are then using the REPLACE function in step 2 to remove them and at the same time converting your date to an integer value.鉴于日期有连字符,然后您在步骤 2 中使用REPLACE function 删除它们,同时将您的日期转换为 integer 值。

Finally, to make sure that steps 1 and 2 work, you can run the following query:最后,为确保第 1 步和第 2 步有效,您可以运行以下查询:

SELECT @dateInt

For today, this will get you the following value: 20210530今天,这将为您提供以下值: 20210530

To make life easier, onw could also create a function:为了让生活更轻松,onw 还可以创建一个 function:

CREATE FUNCTION LastSunday ()
RETURNS int
AS
BEGIN
    RETURN convert(int,dateadd(week,datediff(week,6,getdate()),6))

END
GO

After this you can do:在此之后,您可以执行以下操作:

select dbo.LastSunday();

Which will (now 3th jun 2021 ) result in: 44344这将导致(现在是3th jun 2021 6 月 3 日): 44344

simplest query:最简单的查询:

select cast(replace(cast(getdate() as date),'-','') as int) as DateToInteger

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM