How do I run large SQL scripts that contain many keywords, including “GO” using C#?

て烟熏妆下的殇ゞ 提交于 2019-11-29 15:33:06

Change your ConstructCreatePublicationScript to return a List<string> where each string element is a piece of your complete script splitted at the GO statement. This is necessary because the GO is the separator used by Management Studio and not a SQL statement

public static List<string> ConstructCreatePublicationScript(string rawPublicationScript, string rawAddArticleScript)
{
    .....

    List<string> result = new List<string>();
    result.AddRange(Regex.Split(createPublicationScript, "^GO$", RegexOptions.Multiline));
    return result;
}

then change your execution code to receive the list and execute each single string

public static void CreatePublication(string server, List<string> queries)    
{    
    string finalConnString = Properties.Settings.Default.rawConnectionString.Replace("<<DATA_SOURCE>>", server).Replace("<<INITIAL_CATALOG>>", "tempdb");    

     using (SqlConnection conn = new SqlConnection(finalConnString))    
     {    
         conn.Open();    
         foreach(string query in queries)
         {
             using (SqlCommand cmd = new SqlCommand(query, conn))    
             {    
                 cmd.ExecuteNonQuery();    
             }
         }    
      }    
}

The GO command is not an SQL command, it's a command in SQL Management Studio. It separates batches in a script.

To run the script as SQL, split it on "GO" and execute each string by itself.

(You might want to use a regular expression like \bGO\b or \sGO\s to do the split, so that you catch only occurances that is not part of a word, if you would happen to have an identifier that contains "go".)

read the file. when you come across "GO" submit the query to server (without "GO" itself) and then go on reading.

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