SQL 类似于使用日期 YYYY 的语法

SQL like syntax using date YYYY

我得到了项目财务报告系统的一部分来处理。基本上,我正在尝试修改现有查询以在包含可变日期格式的字段中按日期限制返回结果。

我的查询以 YYYY 格式从别人的代码中发送了两次日期,例如2014 年和 2017 年。在下面的 SQL 查询中,它们被列为 2014 年和 2017 年,因此您只需将它们想象成变量..

数据库中具有可变日期形式的字段有两种形式:YYYYMMDD 或 YYYYMM。

现有查询如下所示:

SELECT   
                    'Expense' AS Type,
                    dbo.Department.Description AS [Country Name],
                    dbo.JCdescription.Description AS Project,
                    dbo.Detail.AccountCode AS [FIN Code], 
                    dbo.JCdescription.ReportCode1 as [Phase Date Start], 
                    dbo.JCdescription.ReportCode2 as [Phase Date End], 
                    dbo.JCdescription.ReportCode3 as [Ratification Date], 
                    dbo.Detail.Year AS [Transaction Year], 
                    dbo.Detail.Period AS [Transaction Year Period], 
                    ...
                FROM
                    dbo.Detail
                INNER JOIN
                    ...
                WHERE
                    (dbo.Detail.LedgerCode = 'jc')
                ...
                AND
                    (dbo.Detail.Year) BETWEEN '2014 AND 2017";

理想情况下,我想将最后一行更改为:

(dbo.JCdescription.ReportCode2 LIKE '[2014-2017]%')

但是这会搜索所有数字 2、0、1、4、5,而不是 2014 到 2017 之间的所有数字。

我敢肯定我一定是遗漏了一些简单的东西,但我找不到了!我意识到我可以将其改写为 LIKE '201[4567]%' 但这意味着 2010-2020 年以外的搜索将出错.. 并要求我开始解析发送的变量,这将引入一个额外的函数,该函数将被多次调用。我宁愿不这样做。我只需要将 2014 和 2017 这两个数字视为整数而不是 4 位数字!

运行 在 MS SQL 服务器 10.0.5520

使用。DATEPART

datepart(year,dbo.Detail.Year) BETWEEN 2014 AND 2017;

我想你可以使用 year system function if your date columns are any of the given date or datetime data types available in SQL Server

这将允许您编写类似于以下内容的内容。

where year(MyDateColumn) between 2014 and 2017

此外,如果您正在使用 varchar as the date column data type, you will have to cast them to the appropriate and comparable values, and you'll also have to make sure to get the only required substring,则需要进行比较。

所以假设您的 dateStringColumn.

中有像“201505”这样的字符串值
where cast(substring(dateStringColumn, 1, 4) as int) between 2014 and 2017

据我了解,您有 2 个用于开始和结束年份的参数来过滤结果。

日期为 YYYYMMYYYYMMDD,您可以使用字符串操作获取前 4 个字符并将其转换为 INT,然后可用于比较到参数。

类似于:

CREATE TABLE #detail ( id INT , SomeDate NVARCHAR(10) )
INSERT  INTO #detail
        ( id, SomeDate )
VALUES  ( 1, '201311' ),
        ( 2, '201402' ),
        ( 3, '20140313' ),
        ( 4, '201409' ),
        ( 5, '201506' ),
        ( 6, '20150912' ),
        ( 7, '201612' ),
        ( 8, '201701' ),
        ( 9, '20181212' )

DECLARE @startYear INT = 2014, @endYear INT = 2017

SELECT *, CONVERT(INT, (LEFT(SomeDate, 4))) AS [Year]
FROM #detail
WHERE CONVERT(INT, (LEFT(SomeDate, 4))) BETWEEN @startYear AND @endYear 

DROP TABLE #detail

根据示例数据,这将产生:

id  SomeDate    Year
====================
2   201402      2014
3   20140313    2014
4   201409      2014
5   201506      2015
6   20150912    2015
7   201612      2016
8   201701      2017

(不包括第 1 行和第 9 行)