[英]SELECT a day before and after SQL
I have the following stored procedure: 我有以下存储过程:
create procedure spListing
(@oMonth int, @oYear int)
AS
BEGIN
SELECT oDate, oValue
FROM oTable
WHERE DATEPART(MONTH, oDate) = @oMonth
AND DATEPART(YEAR, oDate) = @oYear
END
It will select all the value with selected month and year base on given parameter. 它将根据给定参数选择所选月份和年份的所有值。
I want to select 1 day before and after base on given parameter. 我想在给定参数的基础上和之后选择1天。
For example: if @oMonth = '9' and @oYear = '2014' then it will show a list from 31 Aug 2014 until 1 Oct 2014. 例如:如果@oMonth ='9'且@oYear ='2014',则会显示2014年8月31日至2014年10月1日的列表。
Does anyone know how to achieve this? 有谁知道如何实现这一目标?
Thank you. 谢谢。
First find the two dates between which you need to get the data. 首先找到您需要获取数据的两个日期。
DECLARE @oMonth INT=9,
@oYear INT=2014,
@date DATE
SELECT @date = Cast (CONVERT(VARCHAR(4), @oYear) + '-'
+ CONVERT(VARCHAR(2), @oMonth) + '-01' AS DATE)
SELECT Dateadd(day, -1, @date) -- 2014-08-31(Startdate)
SELECT Dateadd(day, 1, Dateadd(day, -Day(@date), Dateadd(month, 1, @date))) --2014-10-01 (Endate)
Now you can use the above queries to filter your result. 现在,您可以使用上述查询来过滤结果。 Change your SP like this.
像这样更改您的SP。
CREATE PROCEDURE Splisting (@oMonth INT,
@oYear INT)
AS
BEGIN
DECLARE @date DATE
SELECT @date = Cast (CONVERT(VARCHAR(4), @oYear) + '-'
+ CONVERT(VARCHAR(2), @oMonth) + '-01' AS DATE)
SELECT oDate,
oValue
FROM oTable
WHERE oDate BETWEEN Dateadd(day, -1, @date)
AND Dateadd(day, 1, Dateadd(day, -Day(@date), Dateadd(month, 1, @date)))
END
I belive this answers your question: 我相信这回答了你的问题:
CREATE PROCEDURE spListing
(@oMonth int, @oYear int)
AS
BEGIN
DECLARE @day int = 1;
DECLARE @startDate date = DATEADD(day,-1,DATEADD(mm, (@oYear - 1900) * 12 + @oMonth - 1 , @day - 1))
DECLARE @endDate date = DATEADD(month,1,DATEADD(mm, (@oYear - 1900) * 12 + @oMonth - 1 , @day - 1))
SELECT oDate, oValue
FROM oTable WHERE oDate
BETWEEN @startDate AND @endDate
END
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.