存储过程参数默认值

时间:2012-08-09 14:43:58

标签: stored-procedures ssms

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

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 ....

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

1 个答案:

答案 0 :(得分: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