在我的表中存储一列(smalldatetime)。
我需要通过提供日期和搜索上面指定的列来检索记录。
Ex:
10/6/2010 4:01:00 PM - 这是Column中的实际值。
我只是想通过今天的日期来搜索表中的记录。 .. ???
ALTER PROCEDURE [dbo].[spDisplayAllOpenPrepaidSales]
@preStatus int,
@preCompanyId int,
@preCounterId int,
@preBillerId int,
@today smalldatetime
AS
BEGIN
print @today
select * from PrepaidSaleHeader
where preOpenStatus = @preStatus And preCompanyId = @preCompanyId And
preCounterId = @preCounterId And preEntryUserId = @preBillerId And preDate > @today
order by preDate
END
并传递参数,如;
spDisplayAllOpenPrepaidSales 0,2,4,2,'10/06/2010 00:00:00 AM'
现在这会撤消记录,但会以24小时格式给我回复日期。
答案 0 :(得分:1)
SQL DateDiff函数是您的朋友 - 请参阅SQL DataDiff Function
ALTER PROCEDURE [dbo].[spDisplayAllOpenPrepaidSales]
@preStatus int,
@preCompanyId int,
@preCounterId int,
@preBillerId int,
@today smalldatetime
AS
BEGIN
print @today
select * from PrepaidSaleHeader
where preOpenStatus = @preStatus And preCompanyId = @preCompanyId And
preCounterId = @preCounterId And preEntryUserId = @preBillerId
And DateDiff(d,preDate,@today) = 0 --to find all dates matching the parameter, regardless of the time
order by preDate
END
答案 1 :(得分:1)
您应该使用符合ISO 8601标准的日期格式,例如
spDisplayAllOpenPrepaidSales 0,2,4,2,'2010-10-06 00:00:00'
时间应该是24小时形式,而不是AM / PM形式,所以我当地的时间现在是'13:02:00'。如果你想要今天的所有记录,因为日期值包括时间,过去今天绝对开始(00:00:00)的任何东西实际上都比今天更大。我总是使用myDate> = today和myDate<明天,转换为:
where preDate >= '2010-10-06' and preDate < '2010-10-07'
为了实现这一点,请使用DATEADD()函数:
where preDate >= @today and preDate < DATEADD(day, 1, @today)
答案 2 :(得分:0)
我会假设您想要检索所有与今天时间部分的日期时间段相匹配的记录?如果是这样,你可以很简单地做一些事情,但这样做很笨拙。
获取列的年份日期和列的年份,并与当前日期的当天和当前日期的年份(或与您比较的任何日期)进行比较。
SELECT * FROM MyTable WHERE DATEPART(dy,MyColumn) = DATEPART(dy,GETDATE()) AND DATEPART(yy,MyColumn) = DATEPART(yy,GETDATE())
所以你的程序看起来像:
ALTER PROCEDURE [dbo].[spDisplayAllOpenPrepaidSales]
@preStatus int,
@preCompanyId int,
@preCounterId int,
@preBillerId int,
@today smalldatetime
AS
BEGIN
print @today
select * from PrepaidSaleHeader
where preOpenStatus = @preStatus And preCompanyId = @preCompanyId And
preCounterId = @preCounterId And preEntryUserId = @preBillerId And DATEPART(dy,preDate) = DATEPART(dy,@today)) AND DATEPART(yy,preDate) = DATEPART(yy,@today)
order by preDate
END