4

我正在尝试使用默认参数创建一个存储过程,在我的查询中我会这样做:

DECLARE @mydate DATETIME
DECLARE @MT DATETIME
DECLARE @MY DATETIME
SELECT @mydate = GETDATE()
SELECT @MT = DATEPART(MONTH,@mydate)
SELECT @MY =  DATEPART(YEAR,@mydate)

SELECT * FROM ....

在我的存储过程中,我尝试如下,但是当我执行存储过程时,它会提示我输入参数值:

USE ..
GO
..
ALTER PROCEDURE ...
(@mydate DATETIME
,@MT DATETIME
,@MY DATETIME)

AS
BEGIN ...
SELECT @mydate = GETDATE()
SELECT @MT = DATEPART(MONTH,@mydate)
SELECT @MY =  DATEPART(YEAR,@mydate)
---
SELECT * FROM ....

如何像在查询中一样在存储过程中设置参数值?

4

1 回答 1

4

尝试这个..

我只放了一个参数,因为其他参数依赖于它。

第一种方法

USE ..
GO
..
ALTER PROCEDURE yourSP
(@mydateParam DATETIME)

AS
BEGIN ...
SELECT @mydate = @mydateParam
SELECT @MT = DATEPART(MONTH,@mydate)
SELECT @MY =  DATEPART(YEAR,@mydate)
  ---
SELECT * FROM ....

调用 SP:

DECLARE @mydateParam DATETIME
SELECT @mydateParam = GETDATE()
execute yourSP @mydateParam

第二种方法

ALTER Procedure yourSP
@mydateParam datetime = null
AS
BEGIN ...
IF @mydateParam is null
SET @mydateParam = getdate()
SELECT @mydate = @mydateParam
SELECT @MT = DATEPART(MONTH,@mydate)
SELECT @MY =  DATEPART(YEAR,@mydate)

   ---
SELECT * FROM ....

调用 SP:

DECLARE @mydateParam DATETIME
SELECT @mydateParam = GETDATE()
execute yourSP @mydateParam

或者

execute yourSP
于 2012-08-09T15:25:05.940 回答