21.07.2009 |
За основу взята статья на форуме SQL.RU /// <summary> /// Выполнение файла SQL-сценария /// </summary> /// <param name="connectionString">Строка соединения</param> /// <param name="CommandTimeOut">Тайм-аут выполнения команды</param> /// <param name="scriptFileName">Имя файла сценария</param> public bool ExecuteSQLScript(string connectionString, int CommandTimeOut, string scriptFileName) { if (!File.Exists(scriptFileName)) { ErrorMessage += "Файл " + scriptFileName + " не найден.\r\n Продолжение невозможно.\r\n"; return false; } // загружаем скрипт String script = File.ReadAllText(scriptFileName, Encoding.GetEncoding(1251)); // делим скрипт на части String []separators = {"GO\r\n"}; String[] idents = script.Split(separators, StringSplitOptions.None); int n_idents = idents.Length; // выполняем части String str_sql = null; using (SqlConnection sqlConn = new SqlConnection(connectionString)) { //SqlConnection sqlConn = new SqlConnection(connectionString); sqlConn.Open(); SqlCommand Command = sqlConn.CreateCommand(); SqlTransaction transaction; // Start a local transaction. transaction = sqlConn.BeginTransaction("LoadSQLTransaction"); Command.Connection = sqlConn; Command.Transaction = transaction; Command.CommandTimeout = CommandTimeOut; try { for (int i = 0; i < n_idents - 1; i++) { str_sql = idents[i]; if (!String.IsNullOrEmpty(str_sql)) { Command.CommandText = str_sql; Command.ExecuteNonQuery(); } } // Attempt to commit the transaction. transaction.Commit(); } catch (Exception ex) { ErrorMessage += String.Format( "Ошибка выполнения скрипта {0}.\r\nНе выполнен фрагмент:\r\n***{1}***\r\nИсключение: {2}\r\n", scriptFileName, str_sql, ex.Message); // Попытка откатить транзакцию try { transaction.Rollback(); } catch (Exception ex2) { // Если возникла ошибка при откате транзакции ErrorMessage += String.Format("Rollback Exception Type: {0}\r\n", ex2.GetType()); ErrorMessage += String.Format("Message: {0}\r\n", ex2.Message); } return false; } } return true; } PS: если Вам была полезна данная статья, поддержите наш ресурс, нажмите кнопочку "+1" вверху страницы. Спасибо!
|
Последнее обновление ( 06.03.2012 )
|