Sql server 如何使用日期作为参数从SQl检索记录
在我的表中,我存储一列(smalldatetime) 我需要通过只给出日期来检索记录,并搜索上面指定的列Sql server 如何使用日期作为参数从SQl检索记录,sql-server,sql-server-2005,Sql Server,Sql Server 2005,在我的表中,我存储一列(smalldatetime) 我需要通过只给出日期来检索记录,并搜索上面指定的列 Ex: 2010年6月10日下午4:01:00-这是列中的实际值 我只想按givin今天的日期搜索表中的记录 ALTER PROCEDURE [dbo].[spDisplayAllOpenPrepaidSales] @preStatus int, @preCompanyId int, @preCounterId int, @preBillerId int, @today smalld
Ex:
2010年6月10日下午4:01:00-这是列中的实际值
我只想按givin今天的日期搜索表中的记录
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小时格式返回日期。SQL DateDiff函数是您的朋友-请参阅
我假设你的意思是你想检索所有与今天的时间段日期相关的记录?如果是这样的话,你可以做一些简单但笨拙的事情 获取第列的日期和第列的年份,并与当前日期的日期和当前日期的年份(或与之比较的任何日期)进行比较 因此,您的程序如下所示:
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
您应该使用符合ISO 8601的日期格式,例如
spDisplayAllOpenPrepaidSales 0,2,4,2,'2010-10-06 00:00:00'
时间应该是24小时的形式,而不是上午/下午的形式,所以我现在的当地时间应该是“13:02:00”。如果您想要今天的所有记录,因为日期值包括时间,超过今天绝对开始(00:00:00)的任何内容实际上都比今天大。我总是使用myDate>=今天和myDate<明天的算法,这意味着:
where preDate >= '2010-10-06' and preDate < '2010-10-07'
其中preDate>='2010-10-06'和preDate<'2010-10-07'
要实现通用性,请使用DATEADD()函数:
where preDate >= @today and preDate < DATEADD(day, 1, @today)
其中preDate>=@今天和preDate
或使用DateDiff…(月份呢…?)当使用一年中的某一天时,月份是不相关的-从1到365。。。DATEDIFF如何处理他在午夜前通过GETDATE的情况?他会得到今天的记录还是过去24小时的记录?对不起,我的错,错过了“dy”:-)DateDiff“计算指定的开始日期和结束日期之间的指定日期部分边界”,因此时间实际上被忽略了-在午夜前经过一段时间,你仍然只得到今天的匹配项。那么你的方法比我的方法更简洁,少做一次比较,更容易打字。。。不确定哪一个会提供更好的性能,但我想你的方法与DATEDIFF。。。投票支持你的答案。。。
where preDate >= '2010-10-06' and preDate < '2010-10-07'
where preDate >= @today and preDate < DATEADD(day, 1, @today)