Pergunta

Is ther a way were we can return 2 values with one variable in SQL Scalar function

ALTER FUNCTION [report].[fGetKPI] (@metricName AS VARCHAR(50))
RETURNS SMALLINT
AS
BEGIN
    DECLARE 
        @kipId AS SMALLINT,
        @metricId as SMALLINT;

    SELECT TOP 1 @kipId = [KPI_Id], @metricId = [MetricId] FROM report.[KPIDetails] WHERE [MetricName] = @metricName;

    IF (@kipId IS NULL OR @metricId IS NULL)
        DECLARE @Error AS INT = dbo.fThrowError('No key found for the component "' + @metricName + '"');
    RETURN (select @kipId,@metricId);
END
Foi útil?

Solução

Scalar functions, by definition, return a single value:

User-defined scalar functions return a single data value of the type defined in the RETURNS clause.

Source: Types of Functions on TechNet

If you want to return more than one value, you should use a table-valued function.

You could also try to somehow pack your two SMALLINT values into one INT or convert them into a string with some separator, but that could get complicated and is not really (in most cases) necessary.

Outras dicas

You can re-write the function as :

IF OBJECT_ID('[report].[fGetKPI]') IS NOT NULL
DROP FUNCTION [report].[fGetKPI];
GO
CREATE FUNCTION [report].[fGetKPI] (@metricName AS VARCHAR(50))
RETURNS TABLE
AS
RETURN 
SELECT TOP 1 [KPI_Id], [MetricId] FROM report.[KPIDetails] WHERE [MetricName] = @metricName;
Go

and then further use dbo.fThrowError by selecting data from function. Hope this helps!!!

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top