0
 If not Exists (Select * from sys.objects where name ='FNLX_getDate' and type =N'FN')
 Create function [dbo].[FNLX_getDate]() returns Datetime
 as
 Begin
 .................
 End

When I execute the above script I get the error

Incorrect syntax near the keyword 'function'.

What can be wrong?

Using Microsoft SQL Server to execute above script.

Paul White
95.4k30 gold badges440 silver badges689 bronze badges
asked Dec 20, 2016 at 9:36
0

2 Answers 2

4

If you are running SQL Server 2016 SP1+, you can use CREATE OR ALTER to avoid conditionally dropping the function beforehand:

CREATE OR ALTER FUNCTION [dbo].[FNLX_getDate]() returns Datetime
AS
BEGIN
...
END;
answered Dec 20, 2016 at 10:55
2

Unfortunately you can't use create function like that. It must be the first statement in a batch.

You can try dynamic SQL instead like:

If not Exists (Select * from sys.objects where name ='FNLX_getDate' and type =N'FN')
 BEGIN
 DECLARE @sql NVARCHAR(MAX);
 SET @sql = N'CREATE FUNCTION ...';
 EXEC sp_executesql @sql;
 END

Or the classic way (like you can see if you generate scripts with SSMS) : drop and create:

If Exists (Select * from sys.objects where name ='FNLX_getDate' and type =N'FN')
 drop function [dbo].[FNLX_getDate]
GO
Create function [dbo].[FNLX_getDate]() returns Datetime
as
Begin
.................
End

Notice the GO SSMS batch separator.

Paul White
95.4k30 gold badges440 silver badges689 bronze badges
answered Dec 20, 2016 at 9:44
2
  • i used dynamic sql but in function i have line Return cast('Timezone conversion: Database timezone should be same as Application timezone or UTC in LU_TimeZoneConfig Table ' as int); when i execute its showing error Msg 102, Level 15, State 1, Line 29 Incorrect syntax near 'Timezone '. Commented Dec 20, 2016 at 9:51
  • @NikhilD You need to have two single quotation marks when building dynamic SQL. For example EXEC('SELECT [MyStringValue] = ''asdf''') Note there are two ' not one " before asdf and three of them after. Commented Aug 12, 2019 at 14:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.