1

I have a .sql file which includes lots of create function and other statements. I put go keyword between them but I got Incorrect Syntaxt Near Go error when I run this by stmt.executeupdate() in java. But when I run it in SSMS 17 I do not get any error. For example here:

GO

IF EXISTS (SELECT *
       FROM   sys.objects
       WHERE  object_id = OBJECT_ID(N'[dbo].[calculateweekday]')
              AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' )) begin
  DROP FUNCTION [dbo].[calculateweekday]
end

GO

create function [dbo].[calculateweekday]
(@inputDate datetime)
returns int as begin
Declare @result int;
Declare @tmp int

select @tmp = (select DATEPART(weekday, @inputDate))
if (@tmp != 1) begin
    select @result = (select @tmp  - 1)
end else begin
    select @result = (select 7)
end
return @result
end

GO

I tried to put this in notepad++ too see if there is something wrong but it look likes same.

I also tried to change the encoding UTF-8 and ANSI but could not solve it. How can I solve this?

JollyRoger
  • 737
  • 1
  • 12
  • 38
  • I think it's your 'GO' it doesn't like it being in a statement sent from a language - I know you can't send it from .net, I forget exactly why – Cato Jul 24 '18 at 11:43
  • 1
    GO is not a part of SQL syntax, its a batch identifier within SSMS (And can be configured to be another word) – Andrew Jul 24 '18 at 11:45
  • Take a look at [this blog post](https://smehrozalam.wordpress.com/2009/05/12/c-executing-batch-t-sql-scripts-with-go-statements/). Bonus: if you are on SQL Server 2016+, you can just use [CREATE OR ALTER](https://blogs.msdn.microsoft.com/sqlserverstorageengine/2016/11/17/create-or-alter-another-great-language-enhancement-in-sql-server-2016-sp1/) instead of using the whole `IF` part. – Rigerta Jul 24 '18 at 11:45
  • https://stackoverflow.com/questions/14473223/execute-dynamic-query-with-go-in-sql – Denis Rubashkin Jul 24 '18 at 11:46
  • @Andrew How can I run the different create statements without getting create functions must be the first statement in query batch error? – JollyRoger Jul 24 '18 at 11:46
  • @JollyRoger Both Rigerta and Denis have provided suitable links. – Andrew Jul 24 '18 at 11:47
  • 1
    Okey I am going to split the statements from GOs, thanks for the answers – JollyRoger Jul 24 '18 at 11:53

0 Answers0