Introduction

In this blog, we are going to learn how to import Excel data into an SQL database table using C#. It also shows how bulk data is inserted into the table, checked for duplicate records, then updated. A stored procedure handles the user-defined table and its implementation. In short, this blog will help to understand bulk insertion of Excel data and the implementation of UDT (User Defined Table in SQL). Let's start now.
Step 1 - Create a database table in SQL
Below is the schema for the table:
  1. CREATE TABLE[dbo].[glsheetdata]
  2. (
  3. [glid] [INT] IDENTITY(1, 1) NOT NULL,
  4. [countryname] [NVARCHAR] (max) NULL,
  5. [company] [NVARCHAR] (max) NULL,
  6. [desc] [NVARCHAR] (max) NULL,
  7. [acctid] [NVARCHAR] (max) NULL,
  8. [accountdesc] [NVARCHAR] (max) NULL,
  9. [custid] [NVARCHAR] (max) NULL,
  10. [site] [NVARCHAR] (max) NULL,
  11. CONSTRAINT[PK_GLSheetData] PRIMARY KEY CLUSTERED ( [glid] ASC )WITH(
  12. pad_index = OFF, statistics_norecompute = OFF, ignore_dup_key = OFF,
  13. allow_row_locks = on, allow_page_locks = on) ON[PRIMARY]
  14. )
  15. ON[PRIMARY]
  16. textimage_on[PRIMARY]
  17. go
Step 2
Create upload Excel .cs class in project:
  1. public class UploadExcel {
  2. public static string DB_PATH = @ "";
  3. public static List < GLSheet > GLDataList = new List < GLSheet > ();
  4. private static Excel.Workbook MyBook = null;
  5. private static Excel.Application MyApp = null;
  6. private static Excel.Worksheet MySheet = null;
  7. private static int lastRow = 0;
  8. public static void InitializeExcel() {
  9. MyApp = new Excel.Application();
  10. MyApp.Visible = false;
  11. MyBook = MyApp.Workbooks.Open(DB_PATH);
  12. MySheet = (Excel.Worksheet) MyBook.Sheets[1]; // Explict cast is not required here
  13. lastRow = MySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
  14. }
  15. public static List < GLSheet > ReadMyExcel() {
  16. try {
  17. GLDataList.Clear();
  18. //First 4 rows are empty and not required. It varies to excel to excel accordingly
  19. for (int rowindex = 5; rowindex <= lastRow; rowindex++) {
  20. //System.Array MyValues = (System.Array)MySheet.get_Range("A" + index.ToString(), "D" + index.ToString()).Cells.Value;
  21. Microsoft.Office.Interop.Excel.Range CountryName = (Microsoft.Office.Interop.Excel.Range) MySheet.Cells[rowindex, 1];
  22. Microsoft.Office.Interop.Excel.Range COMPANY = (Microsoft.Office.Interop.Excel.Range) MySheet.Cells[rowindex, 2];
  23. Microsoft.Office.Interop.Excel.Range Desc = (Microsoft.Office.Interop.Excel.Range) MySheet.Cells[rowindex, 3];
  24. Microsoft.Office.Interop.Excel.Range AcctID = (Microsoft.Office.Interop.Excel.Range) MySheet.Cells[rowindex, 4];
  25. Microsoft.Office.Interop.Excel.Range AccountDesc = (Microsoft.Office.Interop.Excel.Range) MySheet.Cells[rowindex, 5];
  26. Microsoft.Office.Interop.Excel.Range CUSTID = (Microsoft.Office.Interop.Excel.Range) MySheet.Cells[rowindex, 6];
  27. Microsoft.Office.Interop.Excel.Range Site = (Microsoft.Office.Interop.Excel.Range) MySheet.Cells[rowindex, 7];
  28. GLDataList.Add(new GLSheet {
  29. CountryName = Convert.ToString(CountryName.Value),
  30. COMPANY = Convert.ToString(COMPANY.Value),
  31. Desc = Convert.ToString(Desc.Value),
  32. AcctID = Convert.ToString(AcctID.Value),
  33. AccountDesc = Convert.ToString(AccountDesc.Value),
  34. CUSTID = Convert.ToString(CUSTID.Value),
  35. Site = Convert.ToString(Site.Value),
  36. });
  37. //Insert data in slots of 100 rows
  38. UserBusiness userBis = new UserBusiness();
  39. if (rowindex % 100 == 0 || (lastRow - rowindex) < 100) {
  40. bool value = userBis.SaveGLSheetData(GLDataList);
  41. GLDataList = new List < Digiphoto.iMix.ClaimPortal.Model.GLSheet > ();
  42. }
  43. } //For loop completed
  44. } catch (Exception ex) {}
  45. return GLDataList;
  46. }
  47. public static void CloseExcel() {
  48. MyBook.Saved = true;
  49. MyApp.Quit();
  50. }
  51. }
Step 3
Now create the model which is used in the above code:
  1. public class GLSheet
  2. {
  3. public string CountryName { get; set; }
  4. public string COMPANY { get; set; }
  5. public string Desc { get; set; }
  6. public string AcctID { get; set; }
  7. public string AccountDesc { get; set; }
  8. public string CUSTID { get; set; }
  9. public string Site { get; set; }
  10. }
Step 4
Now create a Business logic layer .cs class:
  1. public class UserBusiness : BaseBusiness
  2. {
  3. public bool SaveGLSheetData(List<GLSheet> glSheetData)
  4. {
  5. bool result = false;
  6. this.operation = () =>
  7. {
  8. UserAccess access = new UserAccess(this.Transaction);
  9. result = access.SaveGLSheetData(glSheetData);
  10. };
  11. this.Start(false);
  12. return result;
  13. }
  14. }
Step 5
Create a BaseBusiness .cs class:
  1. public class BaseBusiness
  2. {
  3. #region Declaration
  4. private bool _isTransactionRequired;
  5. public delegate void TransactionMethod();
  6. protected TransactionMethod operation;
  7. public BaseDataAccess m_Access;
  8. private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  9. #endregion
  10. #region Public Methods
  11. public BaseDataAccess Transaction
  12. {
  13. get { return m_Access; }
  14. }
  15. public TransactionMethod Operation
  16. {
  17. set { operation = value; }
  18. }
  19. public BaseBusiness()
  20. {
  21. m_Access = new BaseDataAccess();
  22. }
  23. public BaseBusiness(BaseDataAccess transaction)
  24. {
  25. m_Access = transaction;
  26. }
  27. public virtual void ExecuteOperation(bool isTransactionRequired)
  28. {
  29. try
  30. {
  31. _isTransactionRequired = isTransactionRequired;
  32. if (isTransactionRequired)
  33. {
  34. this.BeginTransaction();
  35. this.operation();
  36. this.Commit();
  37. }
  38. else
  39. {
  40. this.OpenConnection();
  41. this.operation();
  42. // this.CloseConnection();
  43. }
  44. }
  45. catch(Exception ex)
  46. {
  47. RollBack();
  48. //CloseConnection();
  49. log.StartMethod();
  50. if (ex.InnerException != null)
  51. log.Error("ExecuteOperation: " + ex.Message + ex.InnerException + ex.StackTrace.ToString());
  52. else
  53. log.Error("ExecuteDataSet: " + ex.Message + ex.StackTrace.ToString());
  54. log.EndMethod();
  55. throw;
  56. }
  57. finally
  58. {
  59. CloseConnection();
  60. }
  61. }
  62. public bool Start(bool isTransactionRequired)
  63. {
  64. bool success = false;
  65. try
  66. {
  67. this.ExecuteOperation(isTransactionRequired);
  68. success = true;
  69. }
  70. catch(Exception ex)
  71. {
  72. log.StartMethod();
  73. if (ex.InnerException != null)
  74. log.Error("Start: " + ex.Message + ex.InnerException + ex.StackTrace.ToString());
  75. else
  76. log.Error("Start: " + ex.Message + ex.StackTrace.ToString());
  77. log.EndMethod();
  78. throw;
  79. }
  80. return (success);
  81. }
  82. #endregion
  83. #region Private Methods
  84. private void OpenConnection()
  85. {
  86. if (this.m_Access != null)
  87. this.m_Access.OpenConnection();
  88. }
  89. private void CloseConnection()
  90. {
  91. if (this.m_Access != null)
  92. this.m_Access.CloseConnection();
  93. }
  94. private void BeginTransaction()
  95. {
  96. if (this.m_Access != null)
  97. this.m_Access.BeginTransaction();
  98. }
  99. private void Commit()
  100. {
  101. if (this.m_Access != null)
  102. this.m_Access.CommitTransaction();
  103. }
  104. private void RollBack()
  105. {
  106. if (!_isTransactionRequired)
  107. return;
  108. if (this.m_Access != null)
  109. this.m_Access.RollbackTransaction();
  110. }
  111. #endregion
  112. }
Step 6
Create a Data Access layer .cs class:
  1. public class UserAccess : BaseDataAccess
  2. {
  3. #region Constrructor
  4. public UserAccess(BaseDataAccess baseaccess)
  5. : base(baseaccess)
  6. {
  7. }
  8. public UserAccess()
  9. {
  10. }
  11. #endregion
  12. /Save data to SQL database
  13. public bool SaveGLSheetData(List<GLSheet> glSheetData)
  14. {
  15. DBParameters.Clear();
  16. AddParameter("@ParamGLSheetDataUdt", DbHelper.ListToDataTable<GLSheet>(glSheetData));
  17. ExecuteNonQuery("usp_INSAndUPD_GLSheetData");
  18. return true;
  19. }
  20. }
Step 7
Create BaseDataAccess .cs file, which you can use in the application for many different methods
  1. public class BaseDataAccess
  2. {
  3. #region Declaration
  4. private SqlConnection _conn = null;
  5. private SqlCommand _command = null;
  6. private SqlTransaction _trans = null;
  7. private SqlDataAdapter _adapter = null;
  8. private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  9. #endregion
  10. #region Public Properties
  11. public List<SqlParameter> DBParameters { get; set; }
  12. public virtual string MyConString
  13. {
  14. get
  15. {
  16. return ConfigurationManager.ConnectionStrings["iMixClaimConnection"].ConnectionString;
  17. }
  18. }
  19. public SqlTransaction Transaction { get { return _trans; } }
  20. #endregion
  21. #region Constructor
  22. public BaseDataAccess()
  23. {
  24. DBParameters = new List<SqlParameter>();
  25. log4net.Config.XmlConfigurator.Configure();
  26. }
  27. public BaseDataAccess(BaseDataAccess baseAccess)
  28. {
  29. DBParameters = new List<SqlParameter>();
  30. this._conn = baseAccess._conn;
  31. this._trans = baseAccess._trans;
  32. this._adapter = baseAccess._adapter;
  33. }
  34. #endregion
  35. #region Public Methods
  36. protected DataSet ExecuteDataSet(string spName)
  37. {
  38. try
  39. {
  40. DataSet recordsDs = new DataSet();
  41. _command = _conn.CreateCommand();
  42. _command.CommandTimeout = 180;
  43. _command.CommandText = spName;
  44. _command.CommandType = CommandType.StoredProcedure;
  45. _command.Parameters.AddRange(DBParameters.ToArray());
  46. if (_adapter == null)
  47. _adapter = new SqlDataAdapter();
  48. _adapter.SelectCommand = _command;
  49. _adapter.Fill(recordsDs);
  50. return recordsDs;
  51. }
  52. catch (Exception ex)
  53. {
  54. log.StartMethod();
  55. if (ex.InnerException != null)
  56. log.Error("ExecuteDataSet: " + ex.Message + ex.InnerException + ex.StackTrace.ToString());
  57. else
  58. log.Error("ExecuteDataSet: " + ex.Message + ex.StackTrace.ToString());
  59. log.EndMethod();
  60. throw ex;
  61. }
  62. }
  63. protected IDataReader ExecuteReader(string spName)
  64. {
  65. try
  66. {
  67. if (_conn == null)
  68. {
  69. OpenConnection();
  70. }
  71. _command = _conn.CreateCommand();
  72. _command.CommandTimeout = 180;
  73. _command.CommandText = spName;
  74. _command.CommandType = CommandType.StoredProcedure;
  75. _command.Parameters.AddRange(DBParameters.ToArray());
  76. return _command.ExecuteReader();
  77. }
  78. catch (Exception ex)
  79. {
  80. log.StartMethod();
  81. if (ex.InnerException != null)
  82. log.Error("ExecuteReader: " + ex.Message + ex.InnerException + ex.StackTrace.ToString());
  83. else
  84. log.Error("ExecuteReader: " + ex.Message + ex.StackTrace.ToString());
  85. log.EndMethod();
  86. throw;
  87. }
  88. }
  89. protected object ExecuteScalar(string spName)
  90. {
  91. try
  92. {
  93. _command = _conn.CreateCommand();
  94. _command.CommandText = spName;
  95. _command.CommandTimeout = 120;
  96. _command.CommandType = CommandType.StoredProcedure;
  97. _command.Parameters.AddRange(DBParameters.ToArray());
  98. return _command.ExecuteScalar();
  99. }
  100. catch (Exception ex)
  101. {
  102. log.StartMethod();
  103. if (ex.InnerException != null)
  104. log.Error("ExecuteScalar: " + ex.Message + ex.InnerException + ex.StackTrace.ToString());
  105. else
  106. log.Error("ExecuteScalar: " + ex.Message + ex.StackTrace.ToString());
  107. log.EndMethod();
  108. throw ex;
  109. }
  110. }
  111. protected object ExecuteNonQuery(string spName)
  112. {
  113. try
  114. {
  115. _command = _conn.CreateCommand();
  116. _command.CommandText = spName;
  117. _command.CommandTimeout = 120;
  118. _command.CommandType = CommandType.StoredProcedure;
  119. _command.Parameters.AddRange(DBParameters.ToArray());
  120. return _command.ExecuteNonQuery();
  121. }
  122. catch (Exception ex)
  123. {
  124. log.StartMethod();
  125. if (ex.InnerException != null)
  126. log.Error("ExecuteNonQuery: " + ex.Message + ex.InnerException + ex.StackTrace.ToString());
  127. else
  128. log.Error("ExecuteNonQuery: " + ex.Message + ex.StackTrace.ToString());
  129. log.EndMethod();
  130. throw ex;
  131. }
  132. }
  133. #endregion
  134. #region Parameters
  135. protected void AddParameter(string name, object value)
  136. {
  137. DBParameters.Add(new SqlParameter(name, value));
  138. }
  139. protected void AddParameter(string name, object value, ParameterDirection direction)
  140. {
  141. SqlParameter parameter = new SqlParameter(name, value);
  142. parameter.Direction = direction;
  143. DBParameters.Add(parameter);
  144. }
  145. protected void AddParameter(string name, SqlDbType type, int size, ParameterDirection direction)
  146. {
  147. SqlParameter parameter = new SqlParameter(name, type, size);
  148. parameter.Direction = direction;
  149. DBParameters.Add(parameter);
  150. }
  151. protected object GetOutParameterValue(string parameterName)
  152. {
  153. if (_command != null)
  154. {
  155. return _command.Parameters[parameterName].Value;
  156. }
  157. return null;
  158. }
  159. #endregion
  160. #region SaveData
  161. protected bool SaveData(string spName)
  162. {
  163. try
  164. {
  165. if (_conn == null)
  166. {
  167. OpenConnection();
  168. }
  169. _command = _conn.CreateCommand();
  170. _command.CommandTimeout = 180;
  171. _command.CommandText = spName;
  172. _command.CommandType = CommandType.StoredProcedure;
  173. _command.Parameters.AddRange(DBParameters.ToArray());
  174. int result = _command.ExecuteNonQuery();
  175. if (result > 0)
  176. {
  177. return true;
  178. }
  179. else
  180. return false;
  181. }
  182. catch (Exception ex)
  183. {
  184. log.StartMethod();
  185. if (ex.InnerException != null)
  186. log.Error("SaveData: " + ex.Message + ex.InnerException + ex.StackTrace.ToString());
  187. else
  188. log.Error("SaveData: " + ex.Message + ex.StackTrace.ToString());
  189. log.EndMethod();
  190. throw ex;
  191. }
  192. }
  193. #endregion
  194. #region Transaction Members
  195. public bool BeginTransaction()
  196. {
  197. try
  198. {
  199. bool IsOK = this.OpenConnection();
  200. if (IsOK)
  201. _trans = _conn.BeginTransaction();
  202. }
  203. catch (Exception ex)
  204. {
  205. CloseConnection();
  206. log.StartMethod();
  207. if (ex.InnerException != null)
  208. log.Error("BeginTransaction: " + ex.Message + ex.InnerException + ex.StackTrace.ToString());
  209. else
  210. log.Error("BeginTransaction: " + ex.Message + ex.StackTrace.ToString());
  211. log.EndMethod();
  212. throw ex;
  213. }
  214. return true;
  215. }
  216. public bool CommitTransaction()
  217. {
  218. try
  219. {
  220. _trans.Commit();
  221. }
  222. catch (Exception ex)
  223. {
  224. log.StartMethod();
  225. if (ex.InnerException != null)
  226. log.Error("CommitTransaction: " + ex.Message + ex.InnerException + ex.StackTrace.ToString());
  227. else
  228. log.Error("CommitTransaction: " + ex.Message + ex.StackTrace.ToString());
  229. log.EndMethod();
  230. throw ex;
  231. }
  232. finally
  233. {
  234. this.CloseConnection();
  235. }
  236. return true;
  237. }
  238. public void RollbackTransaction()
  239. {
  240. try
  241. {
  242. _trans.Rollback();
  243. }
  244. catch (Exception ex)
  245. {
  246. log.StartMethod();
  247. if (ex.InnerException != null)
  248. log.Error("RollbackTransaction: " + ex.Message + ex.InnerException + ex.StackTrace.ToString());
  249. else
  250. log.Error("RollbackTransaction: " + ex.Message + ex.StackTrace.ToString());
  251. log.EndMethod();
  252. throw ex;
  253. }
  254. finally
  255. {
  256. this.CloseConnection();
  257. }
  258. return;
  259. }
  260. public bool OpenConnection()
  261. {
  262. try
  263. {
  264. if (this._conn == null)
  265. _conn = new SqlConnection(MyConString);
  266. if (this._conn.State != ConnectionState.Open)
  267. {
  268. this._conn.Open();
  269. }
  270. }
  271. catch (Exception ex)
  272. {
  273. log.StartMethod();
  274. if (ex.InnerException != null)
  275. log.Error("OpenConnection: " + ex.Message + ex.InnerException + ex.StackTrace.ToString());
  276. else
  277. log.Error("OpenConnection: " + ex.Message + ex.StackTrace.ToString());
  278. log.EndMethod();
  279. throw ex;
  280. }
  281. return true;
  282. }
  283. public bool CloseConnection()
  284. {
  285. try
  286. {
  287. if (this._conn.State != ConnectionState.Closed)
  288. this._conn.Close();
  289. }
  290. catch (Exception ex)
  291. {
  292. log.StartMethod();
  293. if (ex.InnerException != null)
  294. log.Error("CloseConnection: " + ex.Message + ex.InnerException + ex.StackTrace.ToString());
  295. else
  296. log.Error("CloseConnection: " + ex.Message + ex.StackTrace.ToString());
  297. log.EndMethod();
  298. throw ex;
  299. }
  300. finally
  301. {
  302. if (_conn != null)
  303. {
  304. _conn.Dispose();
  305. this._conn = null;
  306. }
  307. }
  308. return true;
  309. }
  310. #endregion
  311. #region Utility Functions
  312. protected long GetFieldValue(IDataReader sqlReader, string fieldName, long defaultValue)
  313. {
  314. int pos = sqlReader.GetOrdinal(fieldName);
  315. return sqlReader.IsDBNull(pos) ? 0L : sqlReader.GetInt64(pos);
  316. }
  317. protected int GetFieldValue(IDataReader sqlReader, string fieldName, int defaultValue)
  318. {
  319. int pos = sqlReader.GetOrdinal(fieldName);
  320. return sqlReader.IsDBNull(pos) ? 0 : sqlReader.GetInt32(pos);
  321. }
  322. protected float GetFieldValue(IDataReader sqlReader, string fieldName, float defaultValue)
  323. {
  324. int pos = sqlReader.GetOrdinal(fieldName);
  325. //return sqlReader.IsDBNull(pos) ? 0 : sqlReader.GetFloat(pos);
  326. return sqlReader.IsDBNull(pos) ? 0 : (float)sqlReader.GetDouble(pos);
  327. }
  328. //Added on 3-march
  329. protected double GetFieldValue(IDataReader sqlReader, string fieldName, double defaultValue)
  330. {
  331. int pos = sqlReader.GetOrdinal(fieldName);
  332. return sqlReader.IsDBNull(pos) ? 0 : sqlReader.GetDouble(pos);
  333. }
  334. protected decimal GetFieldValue(IDataReader sqlReader, string fieldName, decimal defaultValue)
  335. {
  336. int pos = sqlReader.GetOrdinal(fieldName);
  337. return sqlReader.IsDBNull(pos) ? 0 : sqlReader.GetDecimal(pos);
  338. }
  339. protected string GetFieldValue(IDataReader sqlReader, string fieldName, string defaultValue)
  340. {
  341. int pos = sqlReader.GetOrdinal(fieldName);
  342. return sqlReader.IsDBNull(pos) ? String.Empty : sqlReader.GetString(pos);
  343. }
  344. protected DateTime GetFieldValue(IDataReader sqlReader, string fieldName, DateTime defaultValue)
  345. {
  346. int pos = sqlReader.GetOrdinal(fieldName);
  347. return sqlReader.IsDBNull(pos) ? new DateTime() : sqlReader.GetDateTime(pos);
  348. }
  349. protected bool GetFieldValue(IDataReader sqlReader, string fieldName, bool defaultValue)
  350. {
  351. int pos = sqlReader.GetOrdinal(fieldName);
  352. return sqlReader.IsDBNull(pos) ? false : sqlReader.GetBoolean(pos);
  353. }
  354. #endregion
  355. }
Step 8
Now, the final step to call the required method to upload large or small excel file.
You can upload excel file or directly assign statically if it's fixed and one time activity.
  1. MyExcel.DB_PATH = @"D:\DEI Docs\Bonus Payout\Solution Automation\GL_Actual.csv"; //Here assigned static path, you can assign dynamically by using fileupload
  2. MyExcel.InitializeExcel();
  3. List<GLSheet> lst = MyExcel.ReadMyExcel();
Step 9
Create the below-stored procedure in the SQL database:
  1. CREATE PROCEDURE [dbo].[usp_INSAndUPD_GLSheetData]
  2. (
  3. @ParamGLSheetDataUdt UDT_GLSheetData READONLY
  4. )
  5. AS
  6. /*-------------------------------------------------------------------------------------
  7. AUTHOR : VINOD SALUNKE
  8. DATE CREATED : 8 Aug 2020
  9. PURPOSE/DESCRIPTION :
  10. ---------------------------------------------------------------------------------------
  11. MODIFIED DATE AUTHOR DESCRIPTION
  12. ---------------------------------------------------------------------------------------
  13. TEST CASES:
  14. *------------------------------------------------------------------------------------*/
  15. BEGIN
  16. SET NOCOUNT ON;
  17. DECLARE
  18. @TransactionStarted INT,
  19. @ErrorState INT,
  20. @Msg NVARCHAR(MAX),
  21. @ModifiedBy NVARCHAR(125) = SYSTEM_USER,
  22. @ModifiedDateTime DATETIME= GEtDATE()
  23. DECLARE
  24. @GLData UDT_GLSheetData
  25. IF (@@TRANCOUNT = 0)
  26. BEGIN
  27. SET XACT_ABORT ON;
  28. SET @TransactionStarted = 1;
  29. BEGIN TRANSACTION;
  30. END
  31. BEGIN TRY
  32. MERGE GLSheetData AS Target
  33. USING (SELECT mi.CountryName,mi.COMPANY,mi.[Desc],mi.[AcctID],mi.[AccountDesc],mi.[CUSTID],mi.[Site]
  34. FROM @ParamGLSheetDataUdt mi) AS Source
  35. ON (
  36. Target.[CountryName] = Source.[CountryName]
  37. AND Target.[COMPANY] = Source.[COMPANY]
  38. AND Target.[Desc]=Source.[Desc] AND Target.[AcctID] = Source.[AcctID]
  39. AND Target.[AccountDesc] = Source.[AccountDesc]
  40. AND Target.[CUSTID] = Source.[CUSTID]
  41. AND Target.[Site] = Source.[Site]
  42. )
  43. --WHEN MATCHED THEN
  44. -- UPDATE SET Price = Source.Price,
  45. -- Quantity = Source.Quantity
  46. WHEN NOT MATCHED BY TARGET THEN
  47. INSERT ([CountryName], [COMPANY],[Desc],[AcctID],[AccountDesc],[CUSTID],[Site])
  48. VALUES (Source.[CountryName],Source.[COMPANY],Source.[Desc],Source.[AcctID],Source.[AccountDesc],Source.[CUSTID],Source.[Site]
  49. );
  50. IF ((@TransactionStarted = 1) AND (XACT_STATE() = 1))
  51. COMMIT TRANSACTION;
  52. END TRY
  53. BEGIN CATCH
  54. --Catch Start
  55. SELECT @ErrorState = ERROR_STATE();
  56. SET @Msg = IsNull(ERROR_PROCEDURE(), '[dbo].[usp_INSAndUPD_GLSheetData] ') + ': ' + ERROR_MESSAGE() + ', ' +
  57. 'Line: ' + CONVERT(VARCHAR, ERROR_LINE()) + ', ' +
  58. 'Error: ' + CONVERT(VARCHAR, ERROR_NUMBER()) + ', ' +
  59. 'State: ' + CONVERT(VARCHAR, @ErrorState)
  60. IF ((XACT_STATE() = -1) AND (@TransactionStarted = 1))
  61. BEGIN
  62. ROLLBACK TRANSACTION;
  63. END
  64. ELSE
  65. BEGIN
  66. IF ((XACT_STATE() = 1) AND (@TransactionStarted = 1))
  67. BEGIN
  68. COMMIT TRANSACTION;
  69. END;
  70. END;
  71. RAISERROR(@Msg, 16, 1);
  72. END CATCH;
  73. END
Enjoy coding... :)