Thứ Sáu, 30 tháng 7, 2021

Transaction SQL

Add a try/catch block, if the transaction succeeds it will commit the changes, if the transaction fails the transaction is rolled back: BEGIN TRANSACTION [Tran1] BEGIN TRY INSERT INTO [Test].[dbo].[T1] ([Title], [AVG]) VALUES ('Tidd130', 130), ('Tidd230', 230) UPDATE [Test].[dbo].[T1] SET [Title] = N'az2' ,[AVG] = 1 WHERE [dbo].[T1].[Title] = N'az' COMMIT TRANSACTION [Tran1] END TRY BEGIN CATCH ROLLBACK TRANSACTION [Tran1] SELECT @ErrorMessage = 'Lỗi: ' + ERROR_MESSAGE() RAISERROR(@ErrorMessage, 16, 1) END CATCH ...
Read More »

Move connection string into code

Firstly I had to create myself a new class in my DB ORM assembly Then I had to add a reference to the System.Data.Entity assembly. Then added this static method to my static class (including the namespaces required) using System.Data.SqlClient; using System.Data.EntityClient; namespace MY_DB_ORM { static class MY_DB { public static string ConnectionString() { SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(); // Set the properties for the data source. sqlBuilder.DataSource = "MY_SERVER_IP,1433"; sqlBuilder.InitialCatalog = "MY_DB_NAME"; sqlBuilder.UserID = "MY_USERID"; sqlBuilder.Password = "MY_PASSWORD"; sqlBuilder.IntegratedSecurity = false; // Build...
Read More »

Thứ Ba, 27 tháng 7, 2021

The difference between break and yield break

Using yield break as opposed to break might not be as obvious as one may think. There are lot of bad examples on the Internet where the usage of the two is interchangeable and doesn't really demonstrate the difference. The confusing part is that both of the keywords (or key phrases) make sense only within loops (foreach, while...) So when to choose one over the other? It's important to realize that once you use the yield keyword in a method you effectively turn the method into an iterator. The only purpose of the such method is then to iterate over a finite or infinite collection and yield (output) its elements. Once the purpose is fulfilled, there's no reason to continue method's execution. Sometimes, it happens naturally with the last closing bracket of the method }. But sometimes,...
Read More »