简体   繁体   English

我可以在 like 语句中使用 YEAR(CURDATE()) 吗?

[英]Can I use YEAR(CURDATE()) within a like statement?

In a SQL script I'm trying to get data based on the year within a string value field.在 SQL 脚本中,我试图根据字符串值字段中的年份获取数据。 Each year the table adds a new row for the current year.每年该表都会为当年添加一个新行。 So the ID_TYPE_NAME column has a row with:所以 ID_TYPE_NAME 列有一行:

"MS-DRG V38 (FY 2021)" "MS-DRG V39 (FY 2022)" and so on... “MS-DRG V38(FY 2021)”“MS-DRG V39(FY 2022)”等等...

Being new to SQL I hoped that a formula like the one below would work:作为 SQL 的新手,我希望像下面这样的公式能起作用:

WHERE   ID_TYPE_NAME LIKE 'MS-DRG%'
    and ID_TYPE_NAME LIKE YEAR(CURDATE())

but I get a message that但我收到一条消息

CURDATE is not a recognized built-in function name CURDATE 不是公认的内置 function 名称

Can I use like or do I need to go a different route?我可以使用 like 还是需要 go 不同的路线? If I must go a different route, what method do I use to accomplish this?如果我必须 go 一条不同的路线,我用什么方法来完成这个?

There's nothing magical about LIKE arguments, it's just a regular string where certain characters (namely % and _ ) are handled as wildcard characters. LIKE arguments 并没有什么神奇之处,它只是一个常规字符串,其中某些字符(即%_ )被作为通配符处理。 Your error about CURDATE not being recognized as built-in function is because you're calling a function that doesn't exist, just like if you run select pink_elephants() .关于CURDATE未被识别为内置 function 的错误是因为您正在调用不存在的 function ,就像您运行select pink_elephants()一样。

To compose a string with a pattern that suits your needs you can use these tools:要使用适合您需要的模式组成字符串,您可以使用这些工具:

  • CURRENT_TIMESTAMP to get current date and time (this is a feature from standard SQL that's available in many dialects) CURRENT_TIMESTAMP获取当前日期和时间(这是标准 SQL 的一项功能,可用于许多方言)
  • YEAR() to extract year portion YEAR()提取年份部分
  • CAST() to convert year (an integer) to text CAST()将年份(整数)转换为文本
  • + to concatenate substrings +连接子串

All together:全部一起:

where id_type_name like 'MS-DRG% (FY ' + cast(year(current_timestamp) as varchar(4)) + ')'

Demo演示

We can use CONCAT to build the string which should be found, something like this:我们可以使用CONCAT来构建应该找到的字符串,如下所示:

SELECT ID_TYPE_NAME
FROM yourtable
WHERE ID_TYPE_NAME 
LIKE CONCAT('MS-DRG%',YEAR(GETDATE()),')');

YEAR takes just the year from the whole current date. YEAR只需要从整个当前日期算起的年份。

So the LIKE condition will be created as: MS-DRG%2022)所以LIKE条件将创建为: MS-DRG%2022)

Or we can be even more specific and do this:或者我们可以更具体地做到这一点:

SELECT ID_TYPE_NAME
FROM yourtable
WHERE ID_TYPE_NAME 
LIKE CONCAT('MS-DRG%FY ',YEAR(GETDATE()),')');

The LIKE condition of this query will be created as: MS-DRG%FY 2022)此查询的LIKE条件将创建为: MS-DRG%FY 2022)

Both queries will return only this result from your sample data: MS-DRG V39 (FY 2022)这两个查询都只会从您的示例数据中返回此结果: MS-DRG V39 (FY 2022)

Try out: db<>fiddle尝试: db<>fiddle

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

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