标量值函数中的RETURN语句必须包含参数

时间:2018-02-26 16:43:00

标签: sql-server function

没有设法找到问题的答案。因此,决定在这里分享。希望它能帮助任何人和专业人士分享更有效的解决方案

我在MSSQL中创建了一个函数,它接受一个参数并尝试在映射表中查找相应的记录。映射记录的提取是使用' With子句':

实现的
CREATE FUNCTION [dbo].[GetMappedValue]
(
    @field nvarchar(50) = null
)
RETURNS VARCHAR(50)
AS 
BEGIN
    ;WITH active_mappings AS 
        (SELECT map_key, map_value, ROW_NUMBER() OVER (PARTITION BY map_key ORDER BY updated DESC) AS n
                FROM MappingTable WHERE tag = 'Active')

    RETURN SELECT TOP 1 map_value FROM active_mappings 
           WHERE n=1 AND map_key = @field
END
GO

但是出于一个奇怪的原因:标量值函数中的RETURN语句必须包含一个参数'发生错误

1 个答案:

答案 0 :(得分:1)

为了解决这个问题,我必须声明一个变量并将select的结果赋值给变量,然后才返回它:

CREATE FUNCTION [dbo].[GetMappedValue]
(
    @field nvarchar(50) = null
)
RETURNS VARCHAR(50)
AS 
BEGIN
    Declare @result nvarchar(50)
    ;WITH active_mappings AS 
        (SELECT map_key, map_value, ROW_NUMBER() OVER (PARTITION BY map_key ORDER BY updated DESC) AS n
                FROM MappingTable WHERE tag = 'Active')

    SELECT @Result = (SELECT TOP 1 map_value FROM active_mappings 
           WHERE n=1 AND map_key = @field)

     RETURN @Result
END
GO