我有一个SQL查询,该查询将提取与当前日期(当前设置为今天)匹配的所有数据。
我需要修改它,以便它根据该月的数值拉出一个月内的所有记录。
旧SQL:
WHERE CAST(RecordDate AS DATE) = CAST(GETDATE() AS DATE)
我有一个名为@RecordMonth的入站变量。它是等效于月份的数字(1-12)。我需要提取该数字月份中存在的所有记录。
因此,通过伪编码(带有方括号),查询变为
WHERE CAST(RecordDate AS [MonthPartOfDate]) BETWEEN [FirstDayOf @RecordMonth] AND [LastDayOf @RecordMonth]
有人可以帮忙吗?
答案 0 :(得分:4)
一个简单的方法是:
WHERE YEAR(recorddate) = YEAR(GETDATE()) AND
MONTH(recorddate) = MONTH(GETDATE())
这防止使用索引。要使用索引,我会去:
WHERE recorddate >= DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1) AND
recorddate < DATEADD(month, 1, DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1))
答案 1 :(得分:2)
您可以声明两个变量,以便将其视为单独的startdate
和enddate
:
declare @startdate date = DATEFROMPARTS(YEAR(GETDATE()), MONTH(@RecordMonth), 1)
declare @endddate date = EOMONTH(@startdate)
select . . .
from table t
where (cast(recorddate as date) >= @startdate and
cast(recorddate as date) <= @enddate
);
答案 2 :(得分:0)
后期添加但有用。对于许多系统,将日期保存在内存优化表中很有用。可以将其连接到表中以提供简单,可靠的日期查询:
DECLARE @StartDate DATE = '20000101', @NumberOfYears INT = 30;
-- prevent set or regional settings from interfering with
-- interpretation of dates / literals
SET DATEFIRST 7;
SET DATEFORMAT mdy;
SET LANGUAGE US_ENGLISH;
DECLARE @CutoffDate DATE = DATEADD(YEAR, @NumberOfYears, @StartDate);
-- this is just a holding table for intermediate calculations:
CREATE TABLE [DateTable]
(
[date] DATE PRIMARY KEY,
[day] AS DATEPART(DAY, [date]),
[month] AS DATEPART(MONTH, [date]),
FirstOfMonth AS CONVERT(DATE, DATEADD(MONTH, DATEDIFF(MONTH, 0, [date]), 0)),
[MonthName] AS DATENAME(MONTH, [date]),
[week] AS DATEPART(WEEK, [date]),
[ISOweek] AS DATEPART(ISO_WEEK, [date]),
[DayOfWeek] AS DATEPART(WEEKDAY, [date]),
[quarter] AS DATEPART(QUARTER, [date]),
[year] AS DATEPART(YEAR, [date]),
FirstOfYear AS CONVERT(DATE, DATEADD(YEAR, DATEDIFF(YEAR, 0, [date]), 0)),
Style112 AS CONVERT(CHAR(8), [date], 112),
Style101 AS CONVERT(CHAR(10), [date], 101)
);
-- use the catalog views to generate as many rows as we need
INSERT [DateTable]([date])
SELECT d
FROM
(
SELECT d = DATEADD(DAY, rn - 1, @StartDate)
FROM
(
SELECT TOP (DATEDIFF(DAY, @StartDate, @CutoffDate))
rn = ROW_NUMBER() OVER (ORDER BY s1.[object_id])
FROM sys.all_objects AS s1
CROSS JOIN sys.all_objects AS s2
-- on my system this would support > 5 million days
ORDER BY s1.[object_id]
) AS x
) AS y;
select * from [DateTable]