How do I create a SQL Server function to return an int?

DaveDev picture DaveDev · Jun 7, 2011 · Viewed 67.5k times · Source

I'm trying to create a SQL Function that tests whether a parameter starts with a certain term or contains the term, but doesn't start with it.

Basically, if the parameter starts with the term, the function returns a 0. Otherwise it returns a 1.

This is the bones of the function that I have, which I'm trying to adapt from another function I found:

CREATE FUNCTION [dbo].[fnGetRelevance] 
(   
    @fieldName nvarchar(50),
    @searchTerm nvarchar(50)
)

RETURNS @value int -- this is showing an error, it seems to expect table but all I want is an int
(
    -- does this need to be here? If so, what should it be?
)

AS

BEGIN

    declare @field TABLE(Data nvarchar(50))

    insert into @field
        select Data from @fieldName

    if (Data like @searchTerm + '%') -- starts with
    begin       
        return 0
    end
    else if (Data like '%' + @searchTerm + '%' and Data not like @searchTerm + '%') -- contains, but doesn't start with 
    begin       
        return 1
    end

END

GO

Answer

Alex K. picture Alex K. · Jun 7, 2011

You don't provide a variable name for the return value, just its type, and the parens are not needed;

CREATE FUNCTION [dbo].[fnGetRelevance] 
(   
    @fieldName nvarchar(50),
    @searchTerm nvarchar(50)
)

RETURNS int
AS
....

Also;

select Data from @fieldName

Will not work, you would need dynamic SQL to select from an object the name of which is in a variable.