SqlException: Syntax Error Near 'GO'

牧云@^-^@ 提交于 2019-12-04 02:49:00

问题


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.


回答1:


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.




回答2:


Dave Markle beat me to it. In fact, you can change "GO" to any other string to separate batches.

An alternative implementation here is to use SMO instead of the Entity Framework. There is a useful method there called ExecuteNonQuery that I think will make your life a lot simpler. Here is a good implementation example.




回答3:


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



来源:https://stackoverflow.com/questions/9287321/sqlexception-syntax-error-near-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!