且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何运行包含的关键字,包括&QUOT大型SQL脚本; GO"使用C#?

更新时间:2022-03-23 08:23:49

更改ConstructCreatePublicationScript返回列表<串> 其中每个字符串元素是一块你完整的脚本在GO语句分裂。这是必要的,因为GO是Management Studio中使用的分隔符,而不是一个SQL语句

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;
}

然后更改您的执行code接收清单和执行每个单个

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();    
             }
         }    
      }    
}