将存储过程的结果返回给SQL变量
我有一个名为将存储过程的结果返回给SQL变量,sql,sql-server,stored-procedures,return-value,Sql,Sql Server,Stored Procedures,Return Value,我有一个名为GetLatestUsageFactor801UNR的存储过程,它返回一个精度为18,10的十进制值,但是当我使用下面的代码时,我总是被返回一个零,如何将存储过程的结果设置到变量中,就像在变量保持为零后进行选择一样 DECLARE @UsageFactor801UNR decimal(18,10) EXEC @UsageFactor801UNR = GetLatestUsageFactor801UNR SELECT @UsageFactor801UNR 我正在使用SQL Serve
GetLatestUsageFactor801UNR
的存储过程,它返回一个精度为18,10的十进制值,但是当我使用下面的代码时,我总是被返回一个零,如何将存储过程的结果设置到变量中,就像在变量保持为零后进行选择一样
DECLARE @UsageFactor801UNR decimal(18,10)
EXEC @UsageFactor801UNR = GetLatestUsageFactor801UNR
SELECT @UsageFactor801UNR
我正在使用SQL Server作为我的RDBMS
我的存储过程如下所示:
select TOP 1 TotalUsageFactor as '801 UNR Usage Factor'
from MarketMessage as a
inner join messagetype591 as b on a.MarketMessageID = b.MarketMessageID
inner join AdditionalAggregationInformation as c on b.MessageType591ID = c.MessageType591ID
inner join AdditionalAggregationData as d on c.AdditionalAggregationInformationID = d.AdditionalAggregationInformationID
where SettlementRunIndicator = 20
and LoadProfileCode = 801
and TimeOfUse = 'UNR'
order by SettlementDate desc
通过当前执行,您可以从存储过程的执行中获得返回值,该值是一个整数 这里的一个选项是定义输出参数以从语句中检索值:
-- Stored procedure
CREATE PROCEDURE [GetLatestUsageFactor801UNR]
@UsageFactor801UNR decimal(18, 10) OUTPUT
AS BEGIN
select TOP 1 @UsageFactor801UNR = TotalUsageFactor
from MarketMessage as a
inner join messagetype591 as b on a.MarketMessageID = b.MarketMessageID
inner join AdditionalAggregationInformation as c on b.MessageType591ID = c.MessageType591ID
inner join AdditionalAggregationData as d on c.AdditionalAggregationInformationID = d.AdditionalAggregationInformationID
where SettlementRunIndicator = 20
and LoadProfileCode = 801
and TimeOfUse = 'UNR'
order by SettlementDate desc
END
-- Execution
DECLARE @err int
DECLARE @UsageFactor801UNR decimal(18, 10)
EXECUTE @err = [GetLatestUsageFactor801UNR] @UsageFactor801UNR OUTPUT
IF @err = 0 BEGIN
PRINT 'OK'
PRINT @UsageFactor801UNR
END
ELSE BEGIN
PRINT 'Error'
END
另一个选项是将此存储过程的结果存储在表中。这样就不需要输出参数:
-- Stored procedure
CREATE PROCEDURE [GetLatestUsageFactor801UNR]
AS BEGIN
select TOP 1 TotalUsageFactor AS UsageFactor801UNR
from MarketMessage as a
inner join messagetype591 as b on a.MarketMessageID = b.MarketMessageID
inner join AdditionalAggregationInformation as c on b.MessageType591ID = c.MessageType591ID
inner join AdditionalAggregationData as d on c.AdditionalAggregationInformationID = d.AdditionalAggregationInformationID
where SettlementRunIndicator = 20
and LoadProfileCode = 801
and TimeOfUse = 'UNR'
order by SettlementDate desc
END
-- Execution
DECLARE @UsageFactor801UNR decimal(18, 10)
CREATE TABLE #Temp (UsageFactor801UNR decimal(18, 10))
INSERT INTO #Temp (UsageFactor801UNR)
EXECUTE [GetLatestUsageFactor801UNR]
SELECT @UsageFactor801UNR = UsageFactor801UNR
FROM #Temp
PRINT @UsageFactor801UNR
您使用的是SQL Server吗?您使用的是哪种数据库管理系统?(该代码是特定于产品的。)是的,使用SQL Server时,您应该知道存储过程返回int。如果您有
十进制(18,10)
,则必须是。如何指定输出参数?这是在变量声明中还是在被调用的存储过程中完成的?