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

前端 未结 3 1082
心在旅途
心在旅途 2020-12-21 14:04

I\'m creating a web application that serves as a front end to do SQL Replication.

I have many scripts stored in the properties of the program. Let\'s use the first o

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-21 14:23

    Change your ConstructCreatePublicationScript to return a List 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 ConstructCreatePublicationScript(string rawPublicationScript, string rawAddArticleScript)
    {
        .....
    
        List result = new List();
        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 queries)    
    {    
        string finalConnString = Properties.Settings.Default.rawConnectionString.Replace("<>", server).Replace("<>", "tempdb");    
    
         using (SqlConnection conn = new SqlConnection(finalConnString))    
         {    
             conn.Open();    
             foreach(string query in queries)
             {
                 using (SqlCommand cmd = new SqlCommand(query, conn))    
                 {    
                     cmd.ExecuteNonQuery();    
                 }
             }    
          }    
    }
    

提交回复
热议问题