SqlException: Syntax Error Near 'GO'

前端 未结 3 890
無奈伤痛
無奈伤痛 2021-01-17 11:06

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

I am trying to execute

CREA         


        
相关标签:
3条回答
  • 2021-01-17 11:42

    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

    0 讨论(0)
  • 2021-01-17 11:45

    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.

    0 讨论(0)
  • 2021-01-17 11:59

    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.

    0 讨论(0)
提交回复
热议问题