How do I do a comparison with just a month and year, not a complete date?(如何仅与月份和年份进行比较,而不是完整日期?)
问题描述
我需要编写一个存储过程来允许某人搜索数据库.但是,我得到的只是月份和年份的整数.数据库有月份和年份字段.但我不知道如何设置比较.
I need to write a stored procedure to allow someone to search a db. However, all I get are ints for month and year. And the db has month and year fields. But I can't figure out how to set up the comparison.
例如:我得到 2008 年 3 月和 2010 年 6 月.
Ex: I get March 2008 and June 2010.
我需要在数据库中搜索日期(由月份和年份字段指定)在这两个日期之间的记录.
I need to searhc the database for records where the date, as specified by the month and year fields, are between thoese two dates.
编辑
给定两个 Date 输入,我如何找到落在这些日期之间的所有记录?每条记录只有代表年和月的整数.
Given two Date inputs, how do I find all records that fall between those dates? Each record only has integers representing year and month.
推荐答案
假设您在 SQL Server 中提供了名为 @StartDate 和 @EndDate 的日期变量:
Assuming you are provided Date variables called @StartDate and @EndDate in SQL Server:
SELECT
*
FROM
MyTable
WHERE
-- yields "200901 between 200801 and 201104" on inputs 01-01-2008, 04-01-2011
Convert(VarChar(10), MyTable.Year) + Replace(Str(MyTable.Month, 2), ' ', '0')
BETWEEN
Convert(VarChar(10), YEAR(@StartDate)) + Replace(Str(MONTH(@StartDate), 2), ' ', '0')
AND
Convert(VarChar(10), YEAR(@EndDate)) + Replace(Str(MONTH(@EndDate), 2), ' ', '0')
参考资料
- 简单用于 Int 到字符串转换的左填充 - 受启发的
Replace(Str(MyTable.Month, 2), ' ' , '0') - TSQL 之间
- Simple Left-Padding for Int to String Conversion - Inspired
Replace(Str(MyTable.Month, 2), ' ' , '0') - TSQL Between
这篇关于如何仅与月份和年份进行比较,而不是完整日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何仅与月份和年份进行比较,而不是完整日期
基础教程推荐
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
