SqlException: Syntax Error Near 'GO'

南楼画角 提交于 2019-12-01 15:05:35

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.

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.

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

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