Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlException: Syntax Error Near 'GO'

I am having trouble sending a SQL statement through a DbContext using context.Database.ExecuteSqlCommand().

I am trying to execute

CREATE TABLE Phones([Id] [uniqueidentifier] NOT NULL PRIMARY KEY,
    [Number] [int],[PhoneTypeId] [int])
GO
ALTER TABLE [dbo].[Phones] ADD  CONSTRAINT [DF_Phones_Id]  
    DEFAULT (newid()) FOR [Id]
GO

This fails with the error string

Incorrect syntax near the keyword 'ALTER'.
Incorrect syntax near 'GO'.

However running that exact statement in SSMS runs without errors? Any issues I need to resolve regarding the default constraint throught the DbContext. I have see problems with people using constraints and not having IsDbGenerated set to true. I am not sure how that would apply here though.

like image 855
bdparrish Avatar asked Feb 15 '12 03:02

bdparrish


2 Answers

GO is not a part of SQL, so it can't be executed with ExecuteSqlCommand(). Think of GO as a way to separate batches when using Management Studio or the command-line tools. Instead, just remove the GO statements and you should be fine. If you run into errors because you need to run your commands in separate batches, just call ExecuteSqlCommand() once for each batch you want to run.

like image 166
Dave Markle Avatar answered Sep 29 '22 22:09

Dave Markle


I know, necroposting is bad maner, but may be this post would save someone's time. As it was mentioned in Dave's post, GO is not a part of SQL, so we can create little workaround to make it work

            var text = System.IO.File.ReadAllText("initialization.sql");
            var parts = text.Split(new string[] { "GO" }, System.StringSplitOptions.None);
            foreach (var part in parts) { context.Database.ExecuteSqlCommand(part); }

            context.SaveChanges();

In this case your commands would be splitted and executed without problems

like image 35
V319 Avatar answered Sep 29 '22 21:09

V319