如何使用具有默认值的多个输入创建存储过程?

时间:2019-07-15 20:10:06

标签: sql-server stored-procedures

我试图创建一个存储过程,该过程需要两个值,即开始和结束行值。默认开始应为从选择视图返回的行数,结束应为从开始算起的60个值。我遇到的问题是使用参数声明两个值(如果未传递任何参数)并进一步使用这些值。

我尝试使用声明并且没有运气。

CREATE PROCEDURE [dbo].[getRecords] 
    (@StartLoc INT = (SELECT COUNT(*) FROM [dbo].[dashboardview]),
     @EndLoc INT = @StartLoc - 60)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT         
        o.ID, o.Name, o.DateRan, s.Name AS Job, o.Start, o.[End],
        o.Status, o.Logs 
    FROM            
        dbo.output AS o
    LEFT OUTER JOIN 
        dbo.jobs AS j ON o.Job = j.ID
    LEFT OUTER JOIN 
        dbo.scripts AS s ON  j.Script = s.ID 
    WHERE 
        (o.DateRan < GETDATE()) 
        AND (ROW_NUMBER() >= @StartLoc And ROW_NUMBER()<= @EndLoc)
    ORDER BY 
        o.ID
END

我的目的是返回指定范围之间的记录数。

2 个答案:

答案 0 :(得分:2)

将“默认值”设置为NULL,然后检查是否将这些值设置为NULL:

CREATE PROCEDURE [dbo].[getRecords] 
  @StartLoc INT = NULL,
  @EndLoc INT = NULL
AS
BEGIN
  SET NOCOUNT ON;

  IF @StartLoc IS NULL 
    SET @StartLoc = (SELECT COUNT(*) FROM [dbo].[dashboardview]);

  IF @EndLoc IS NULL
    SET @EndLoc = @StartLoc - 60;

  ...

答案 1 :(得分:2)

认为,这可能是OP所需要的...如果说实话,这很难说:

CREATE PROCEDURE [dbo].[getRecords] @StartLoc INT = NULL,@EndLoc INT = NULL
AS BEGIN
     SET NOCOUNT ON;

     IF @StartLoc IS NULL BEGIN
          SET @StartLoc = 0;
     END ELSE BEGIN
          SET @StartLoc = @StartLoc - 1;
     END;

     IF @Endloc IS NULL BEGIN
          SELECT @EndLoc = COUNT(*) FROM [dbo].[dashboardview];
     END ELSE BEGIN
          SET @EndLoc = @Endloc - @StartLoc
     END;

     SELECT o.ID,
            o.Name,
            o.DateRan,
            s.Name AS Job,
            o.Start,
            o.[End],
            o.Status,
            o.Logs 
     FROM  dbo.output AS o 
               LEFT OUTER JOIN dbo.jobs AS j ON o.Job = j.ID
               LEFT OUTER JOIN dbo.scripts AS s ON j.Script = s.ID 
     WHERE (o.DateRan < GETDATE()) 

     ORDER BY o.ID
     OFFSET @StartLoc ROW FETCH NEXT @EndLoc ROWS ONLY;
END
GO

理想情况下,@EndLoc的逻辑应该是行数而不是结束位置,因为这意味着您不需要更改值(@startLoc应该以0开始,而不是1开始)。