存储过程使用默认参数

时间:2016-07-01 15:33:53

标签: sql-server tsql stored-procedures parameters

我正在尝试根据我使用预定义参数编写的查询创建存储过程。

重构到创建存储过程并执行存储过程时,它指出未提供参数。谁能告诉我为什么?

我知道我已经错过了一些必要的东西但是在弄乱了代码之后我已经达到了需要专家帮助的程度。

这是我的代码(缩短):

Alter Procedure [Test]
    @StartDate AS varchar(6), 
    @EndDate AS varchar(6)
AS
    Set @StartDate = '201620' --Define start YearWeek
    Set @EndDate  = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))

    SELECT 
        *
    FROM
        (SELECT DISTINCT 
             [YEAR], [WeekOfYear] 
         FROM 
             [dbo].[DimDate] 
         WHERE 
             [Year] + [WeekOfYear] BETWEEN @StartDate AND @EndDate) dimd
    LEFT JOIN 
        [Schema].[Table1] qad ON (qad.[Year] + qad.[Week of the Year]) = (dimd.[Year] + dimd.WeekOfYear)

当我运行程序时,我得到:

  

Msg 201,Level 16,State 4,Procedure test,Line 0
  过程或函数'test'需要参数'@StartDate',而不是   提供。

提前致谢。

2 个答案:

答案 0 :(得分:25)

  

我用预定义的参数写了

它们不是逻辑上的“预定义”,代码中的某个位置。但作为SP的参数,它们没有默认值并且是必需的。为了避免明确地传递这些参数,您必须在SP定义中定义默认值:

Alter Procedure [Test]
    @StartDate AS varchar(6) = NULL, 
    @EndDate AS varchar(6) = NULL
AS
...

NULL或空字符串或更合理的东西 - 取决于您。因为你在SP的第一行覆盖了那些参数的值,所以没关系。

现在你可以在不传递任何参数的情况下调用它,例如 exec dbo.TEST

答案 1 :(得分:1)

我会这两种方式中的一种。由于您在t-sql代码中设置了开始日期和结束日期,我不会在存储过程中询问参数

选项1

Create Procedure [Test] AS
    DECLARE @StartDate varchar(10)
    DECLARE @EndDate varchar(10)
    Set @StartDate = '201620' --Define start YearWeek
    Set @EndDate  = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

选项2

Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

然后运行exec test '2016-01-01','2016-01-25'