简体   繁体   English

SQL Server:使用参数代替GETDATE()

[英]SQL Server: use parameter instead of GETDATE()

I have a stored procedure that uses selects like the following which works fine so far. 我有一个使用以下选择的存储过程,到目前为止效果很好。 In this case for example it selects all records with a date from the previous month, ie March 2014 (column: dateEsc, formatted as nvarchar(20) , example date: 2014-03-25). 例如,在这种情况下,它将选择所有日期为上个月(即2014年3月)的记录(列:dateEsc,格式为nvarchar(20) ,示例日期:2014-03-25)。

My Select (example): 我的选择(示例):

SELECT COUNT(*) AS groupCount
FROM Log_Esc
WHERE 
    CONVERT(DATE, dateEsc, 120) >= CONVERT(DATE, CONVERT(VARCHAR(6), DATEADD(month, -1, GETDATE()), 112) + '01', 112)

How do I have to change this if instead of the current Date (GETDATE()) I want to use a variable date input as the reference. 如果要使用可变日期输入作为参考,而不是当前日期(GETDATE()),如何更改此设置。 This input would be any date and is formatted as nvarchar(20) as well, example: 2014-04-03. 此输入可以是任何日期,并且其格式也为nvarchar(20) ,例如:2014-04-03。

So instead of calculating the previous month compared to the current month from GETDATE() I would like to calculate the same from the variable date input. 因此,我不想从GETDATE()计算上个月与当前月份相比,而是想从可变日期输入中计算出同一月份。

Many thanks for any help with this, Tim. 蒂姆,非常感谢您对此提供的任何帮助。

First of all I think this query is better than the one you have: 首先,我认为此查询比您拥有的查询要好:

SELECT COUNT(*) AS groupCount
FROM Log_Esc
WHERE DATE >= dateadd(month,datediff(month,0,dateadd(month,GETDATE(),-1)),0)
 AND  DATE <  dateadd(month,datediff(month,0,GETDATE()),0)

If there is an index on the DATE field this can do a seek. 如果DATE字段上有索引,则可以执行查找。

If you have a parameter @indate defined as date or datetime then this will work 如果您将参数@indate定义为date或datetime,那么它将起作用

SELECT COUNT(*) AS groupCount
FROM Log_Esc
WHERE DATE >= dateadd(month,datediff(month,0,dateadd(month,@indate,-1)),0)
 AND  DATE <  dateadd(month,datediff(month,0,@indate),0)

See this question for more information on flooring a date to a month: Floor a date in SQL server 有关将日期限制为一个月的更多信息,请参见此问题: 在SQL Server中限制日期

So what you want is a parameter: 因此,您想要的是一个参数:

Specifying Parameters in a Stored Procedure 在存储过程中指定参数

Parameters allow you to pass user input to modify output. 参数允许您传递用户输入以修改输出。

An example 一个例子

CREATE PROCEDURE dbo.Param1
@param int 
AS
BEGIN

select 7 *@param as Value
END

EXEC dbo.Param1 5 -- 7 *5
EXEC dbo.Param1 -10  -- 7 * -10

Perhaps this'll give you some creative ideas for how you might implement parameters to accomplish your group count. 也许这会为您提供一些有关如何实现参数以完成组数的创意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM