How to return varchar value from a function

后端 未结 2 847
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-01 14:14

I written the following function.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create FUNCTION NameFunction
(
    @eid int
)
RETURNS varchar
AS
BEGIN
            


        
相关标签:
2条回答
  • 2021-01-01 14:35

    Change your RETURN type to include a length, at this point it is just returning 1 character:

    RETURNS varchar(100)
    

    Full code:

    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    Create FUNCTION NameFunction
    (
        @eid int
    )
    RETURNS varchar(100) -- or whatever length you need
    AS
    BEGIN
        Declare @logid varchar(50);
        SELECT @logid = E.LoginId from HumanResources.Employee As E
        where E.BusinessEntityID = @eid
    
        RETURN  @logid
    
    END
    GO
    
    0 讨论(0)
  • 2021-01-01 14:51

    RETURNS varchar should be RETURNS varchar(50).

    varchar without a length specified is interpreted as varchar(1) in this context (and as varchar(30) in the context of a CAST).

    BTW: Scalar UDFs that do data access can be performance killers. You might want to consider at least rewriting this as an inline TVF so that the optimiser has more options.

    0 讨论(0)
提交回复
热议问题