存储过程返回值

non*_*one 4 sql-server stored-procedures

使用此代码:

ALTER PROCEDURE [dbo].[get](@i int)
AS
BEGIN
    declare @ADate datetime
    select @ADate = ADate 
    from table
    where i=@i
    and DateDiff(day ,getDate(), aDate  ) > 0
    and aDate is not null
    order by aDate asc
    return select @ADAte   
END
Run Code Online (Sandbox Code Playgroud)

这将返回0(或系统0日期时间,这不是数据库的预期结果).

执行代码

Declare @res datetime

exec @res = get 3

print @res
Run Code Online (Sandbox Code Playgroud)

为什么?

RBa*_*ung 9

SQL Server中的存储过程只能返回整数.如果您需要返回除单个整数之外的任何内容,那么您应该使用这些方法之一(有些方法由前面的答案解释):

  • 在您的过程中使用SELECT

  • 使用OUTPUT参数

  • 请改用用户定义的函数


cod*_*ger 7

无需声明变量并为其赋值.只需返回select语句.

ALTER PROCEDURE [dbo].[get](@i int)
AS
BEGIN

    select ADate 
    from table
    where i=@i
    and DateDiff(day ,getDate(), aDate  ) > 0
    and aDate is not null
    order by aDate asc

END
Run Code Online (Sandbox Code Playgroud)

虽然您应该知道,根据您的数据,这可能会返回多个值.

编辑

如果你愿意,你可以这样做:

ALTER PROCEDURE [dbo].[get](@i int, @date datetime output)
AS
BEGIN

    select @date = ADate 
    from table
    where i=@i
    and DateDiff(day ,getDate(), aDate  ) > 0
    and aDate is not null
    order by aDate asc

END
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它:

Declare @res datetime

exec get 3, @res

print @res
Run Code Online (Sandbox Code Playgroud)