[英]Calculating variances on dates in T-SQL
伙計們,我正在嘗試在T-SQL(SQL Server)中編寫一個存儲過程,該存儲過程將基於日期字段選擇記錄,並牢記分鍾的變化。 像這樣:
CREATE PROCEDURE spGetCustomers(@DateRange DATETIME, @Variance int) AS
-- The next line is where I need help
-- I'm trying to subtract X amount of minutes from the date
-- So if @Variance = 4 AND @DateRange = '6/10/2009 1:15pm'
-- Then @StartDate should equal '6/10/2009 1:11pm'
DECLARE @StartDate = @DateRange - @Variance
-- I also need an @EndDate, which will be X amount of minutes
-- in the future. So if @Variance = 4 AND @DateRange = '6/10/2009 1:15pm'
-- Then @EndDate should equal '6/10/2009 1:19pm'
DECLARE @EndDate = @DateRange + @Variance
SELECT * FROM Customers WHERE Created BETWEEN @StartDate AND @EndDate
希望這是有道理的,有人可以幫助我! 提前致謝
看一下這個:
http://msdn.microsoft.com/zh-CN/library/ms186819(SQL.90).aspx
DATEADD函數允許您將日期的幾乎任何部分添加到另一個日期對象,這應該是您需要的所有內容。
所以基本上可以這樣做:
SELECT DATEADD(second, @Variance, @DateRange)
以下腳本提供了一個入門示例。
create table tmp_Customers
(
ID int identity(1,1),
CreatedDate datetime default getDate() not null,
Description varchar(15)
);
go
insert into tmp_Customers(Description) values('SomeData');
insert into tmp_Customers(Description) values('SomeData2');
insert into tmp_Customers(Description) values('SomeData3');
go
create procedure usp_GetCustomers
@iVarianceMinutes int,
@iDateRange datetime
as
set nocount on
declare @startDate datetime
declare @endDate datetime
--Define the date ranges for the select query
set @startDate = dateAdd(minute,-@iVarianceMinutes,@iDateRange)
set @endDate = dateAdd(minute,@iVarianceMinutes,@iDateRange)
--Get the Customers that were created within this time range.
SELECT *
FROM tmp_Customers
WHERE CreatedDate >= @startDate and CreatedDate < @endDate
return(0);
go
--Execute the procedure
declare @testDate datetime;
set @testDate = getDate();
exec usp_GetCustomers 5,@testDate
--drop procedure usp_GetCustomers
--drop table tmp_Customers
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.