Create Function Must Be the Only Statement in the Batch
I'm Getting This Error from the Function: Create Function getLavel(@id Int, @Lavel Char) Returns Date Begin Declare @Date Date Select @Date = (Select...
I'm getting this error from the function:
CREATE FUNCTION getLavel(@id int ,@lavel char)
RETURNS date
BEGIN
DECLARE @date date
select @date = (select authorization_date from Authorized WHERE diver_number = @id and @lavel =level_name)
return @date
END
GO
What can be the reason?
Ty very much.
7 Answers
The function needs to be either the only function in the query window OR the only statement in the batch. If there are more statements in the query window, you can make it the only one "in the batch" by surrounding it with GO's.
e.g.
GO
CREATE FUNCTION getLavel(@id int ,@lavel char)
RETURNS date
BEGIN
DECLARE @date date
select @date = (select authorization_date from Authorized WHERE diver_number = @id and @lavel =level_name)
return @date
END
GO
Turn this into an inline table valued function. This will perform better than the scalar function. Also, you should NOT use the default sizes for character datatypes. Do you know what the default length for a char is? Did you know that it can vary based on usage?
CREATE FUNCTION getLavel
(
@id int
, @lavel char --You need to define the length instead of the default length
)
RETURNS table
return
select authorization_date
from Authorized
WHERE diver_number = @id
and @lavel = level_name
GO
You need to add RETURN before the END statement
That should fix your issue, that's what fixed mine. :D
Make sure that this statement is the only the only sql in your query window before you execute it.
Or you can highlight the function declaration and execute
What solved it for me, was that I was trying to create the function inside of a transaction context - that doesn't make sense from a SQL Server point of view. Transactions are for data, not functions.
Take the CREATE FUNCTION statement out of the transaction, then wrap it in GO's
CREATE FUNCTION CalculateAge(@DOB DATE)
RETURNS INT
AS
BEGIN
DECLARE @Age INT
SET @DOB='08/12/1990'
SET @Age =DATEDIFF(YEAR,@DOB,GETDATE()) -
CASE
WHEN (MONTH (@DOB)> MONTH (GETDATE ())) OR
(MONTH (@DOB)= MONTH (GETDATE ()) AND DAY (@DOB) >DAY (GETDATE ()))
THEN 1
ELSE 0
END
SELECT @Age
END
The Error is given to you in only query Page But if you execute the query then it will successfully execute.
CREATE FUNCTION getLavel(@id int ,@lavel char)
RETURNS date
BEGIN
DECLARE @date date
select @date = (select authorization_date from Authorized WHERE diver_number = @id and @lavel = level_name)
return @date
END
GO