Kadaj13
Kadaj13

Reputation: 1541

Defining a function in sql server

I want to declare a function in SQL SERVER, It is the beginning of my code, but I get this error: 'CREATE FUNCTION' must be the only statement in the batch.

CREATE FUNCTION FindingMobileOrTelephone ( @Number nchar(11) )
RETURNS nvarchar
AS
BEGIN
    DECLARE @ItIsMobile nvarchar;
    DECLARE @ItIsTelephone nvarchar;
    RETURNS @ItIsMobile;
END;

what is the problem?!

Upvotes: 1

Views: 89

Answers (2)

Kirill Slatin
Kirill Slatin

Reputation: 6143

CREATE FUNCTION/TABLE should be the first statement in the script you're executing.

One option was already mentioned. Adding GO kind of splits the script into separate ones.

However, if you have this within BEGIN END block this won't work since you can't split this block with GO. An option here is to wrap CREATE statment into a string literal and use EXEC or sp_executesql

-- your script
EXEC('CREATE FUNCTION ... END')

Upvotes: 1

Dgan
Dgan

Reputation: 10285

try this

Last Statement Should be RETURN not RETURNS

CREATE FUNCTION FindingMobileOrTelephone ( @Number nchar(11) )
RETURNS nvarchar
AS
BEGIN
    DECLARE @ItIsMobile nvarchar;
    DECLARE @ItIsTelephone nvarchar;
    RETURN (@ItIsMobile);
    ^

END 

Upvotes: 1

Related Questions