无法在函数中连接变量

时间:2016-07-01 23:37:09

标签: sql sql-server sql-server-2008-r2

我在SQL Server 2008 R2上运行。我想编写一个标量函数来连接地址的各个部分并返回格式化的结果以便在屏幕上显示。但我所得到的只是@Address变量 - 城市,州,邮政,国家从未添加到价值中。这应该很简单;我做错了什么?

这是我的标量函数:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
;

ALTER FUNCTION [dbo].[fnScreenAddress] (@Id INT)
RETURNS VARCHAR(50)
WITH EXECUTE AS CALLER
AS
BEGIN
    DECLARE @ScreenAddress VARCHAR(50), -- The return value
            @Address VARCHAR(64),
            @UnitNumber VARCHAR(16),
            @City VARCHAR(50),
            @State CHAR(2),
            @PostalCode VARCHAR(16),
            @CountryCode VARCHAR(16);

    SELECT  
        @Address = [Address],
        @UnitNumber = ISNULL([UnitNumber], ''),
        @City = [City],
        @State = [State],
        @PostalCode = [PostalCode],
        @CountryCode = ISNULL([CountryCode], '')
    FROM    
        [dbo].[LPAddress]
    WHERE   
        [ID] = @Id;

    SET @ScreenAddress = @Address;

    IF @City <> ''
    BEGIN
        SET @ScreenAddress = @ScreenAddress + ', ';
    END;

    SET @ScreenAddress = @ScreenAddress + @City;

    IF @State <> ''
    BEGIN
        SET @ScreenAddress = @ScreenAddress + ', ';
    END;

    SET @ScreenAddress = @ScreenAddress + @State;
    SET @ScreenAddress = @ScreenAddress + @PostalCode;
    SET @ScreenAddress = @ScreenAddress + @CountryCode;
    SET @ScreenAddress = LTRIM(RTRIM(@ScreenAddress));

    RETURN(@ScreenAddress);
END;

要测试它,我在查询窗口中输入以下命令:

select 
    id, address, city, state, postalcode, countrycode, 
    dbo.fnScreenAddress(id) as [ScreenAddress]
from 
    lpaddress;

我得到了这个结果集:

enter image description here

1 个答案:

答案 0 :(得分:1)

更简单的版本看起来像......

ALTER FUNCTION [dbo].[fnScreenAddress]
(
    @Id                 INT
)
RETURNS VARCHAR(4000)
WITH EXECUTE AS CALLER
AS
BEGIN
        DECLARE @ScreenAddress VARCHAR(4000); -- The return value

SELECT  @ScreenAddress = 
    STUFF(  
        ISNULL( ', ' + NULLIF([Address]    , '')  , '')
      + ISNULL( ', ' + NULLIF([UnitNumber] , '')  , '')
      + ISNULL( ', ' + NULLIF([City]       , '')  , '')
      + ISNULL( ', ' + NULLIF([State]      , '')  , '')
      + ISNULL( ', ' + NULLIF([PostalCode] , '')  , '')
      + ISNULL( ', ' + NULLIF([CountryCode], '')  , '') , 1,2,'')
FROM    [dbo].[LPAddress]
WHERE   [ID] = @Id

        RETURN @ScreenAddress;
END;

重要提示

我不会为此目的使用标量函数,标量函数是性能杀手,特别是在这种特定情况下,函数将被调用为您的选择将返回的行数。可能只是在您的选择查询中添加函数的代码以获得更好的性能。