views:

39

answers:

2

How do you assign the result of an exec call to a variable in sql? I have a stored proc called up_GetBusinessDay, which returns a single date. Can you do something like this:

exec @PreviousBusinessDay = dbo.up_GetBusinessDay @Date, -1

Thanks.

+1  A: 

From the documentation (assuming that you use SQL-Server):

USE AdventureWorks;
GO
DECLARE @returnstatus nvarchar(15);
SET @returnstatus = NULL;
EXEC @returnstatus = dbo.ufnGetSalesOrderStatusText @Status = 2;
PRINT @returnstatus;
GO

So yes, it should work that way.

Peter Lang
in the OP's example they want to return a date, Stored procedures can only RETURN an integer value to a calling procedure or an application.
KM
+2  A: 

I always use the return value to pass back error status. If you need to pass back one value I'd use an output parameter.

sample stored procedure, with an OUTPUT parameter:

CREATE PROCEDURE YourStoredProcedure 
(
    @Param1    int
   ,@Param2    varchar(5)
   ,@Param3    datetime OUTPUT
)
AS
IF ISNULL(@Param1,0)>5
BEGIN
    SET @Param3=GETDATE()
END
ELSE
BEGIN
    SET @Param3='1/1/2010'
END
RETURN 0
GO

call to the stored procedure, with an OUTPUT parameter:

DECLARE @OutputParameter  datetime
       ,@ReturnValue      int

EXEC @ReturnValue=YourStoredProcedure 1,null, @OutputParameter OUTPUT
PRINT @ReturnValue
PRINT CONVERT(char(23),@OutputParameter ,121)

OUTPUT:

0
2010-01-01 00:00:00.000
KM
By using an OUTPUT parameter, you can return back any data type, the RETURN value from a stored procedure can only be an integer.
KM
+1: Agreed, thanks for your comment.
Peter Lang