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
这篇关于如何仅与月份和年份进行比较,而不是完整日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何仅与月份和年份进行比较,而不是完整日期


基础教程推荐
- SQL Server 2016更改对象所有者 2022-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01