SQL Transactions

Transactions in SQL Server are very useful, however I have come across that not many people use them. Not sure why this could be, so thought I would share how transactions work and the different modes.

A transaction is a single unit of work. If a transaction is successful, all of the data modifications made during the transaction are committed and become a permanent part of the database. If a transaction encounters errors and must be canceled or rolled back, then all of the data modifications are erased.

SQL Server operates in the following transaction modes:
Autocommit transactions
Each individual statement is a transaction.

Explicit transactions
Each transaction is explicitly started with the BEGIN TRANSACTION statement and explicitly ended with a COMMIT or ROLLBACK statement.

Implicit transactions
A new transaction is implicitly started when the prior transaction completes, but each transaction is explicitly completed with a COMMIT or ROLLBACK statement.

Batch-scoped transactions
Applicable only to multiple active result sets (MARS), a Transact-SQL explicit or implicit transaction that starts under a MARS session becomes a batch-scoped transaction. A batch-scoped transaction that is not committed or rolled back when a batch completes is automatically rolled back by SQL Server.

From my experience Explicit transactions are the most commonly used out of all the different modes.

Distributed Transactions:
You can use Distributed transactions which specifies the start of a SQL distributed transaction managed by Microsoft Distributed Transaction Coordinator (MS DTC). This is only applicable to SQL Server and no Azure. Transaction-level snapshot isolation does not support distributed transactions.

Arguments:
transaction_name
Is a user-defined transaction name used to track the distributed transaction within MS DTC utilities. transaction_name must conform to the rules for identifiers and must be <= 32 characters.

@tran_name_variable
Is the name of a user-defined variable containing a transaction name used to track the distributed transaction within MS DTC utilities. The variable must be declared with a char, varchar, nchar, or nvarchar data type.

The instance of the SQL Server Database Engine executing the BEGIN DISTRIBUTED TRANSACTION statement is the transaction originator and controls the completion of the transaction. When a subsequent COMMIT TRANSACTION or ROLLBACK TRANSACTION statement is issued for the session, the controlling instance requests that MS DTC manage the completion of the distributed transaction across all of the instances involved.

For example, if BEGIN DISTRIBUTED TRANSACTION is issued on ServerA, the session calls a stored procedure on ServerB and another stored procedure on ServerC. The stored procedure on ServerC executes a distributed query against ServerD, and then all four computers are involved in the distributed transaction. The instance of the Database Engine on ServerA is the originating controlling instance for the transaction.

USE AdventureWorks2012;  
GO  
BEGIN DISTRIBUTED TRANSACTION;  
-- Delete candidate from local instance.  
DELETE AdventureWorks2012.HumanResources.JobCandidate  
    WHERE JobCandidateID = 13;  
-- Delete candidate from remote instance.  
DELETE RemoteServer.AdventureWorks2012.HumanResources.JobCandidate  
    WHERE JobCandidateID = 13;  
COMMIT TRANSACTION;  
GO  

Begin Transaction
Marks the starting point of an explicit, local transaction. Explicit transactions start with the BEGIN TRANSACTION statement and end with the COMMIT or ROLLBACK statement. BEGIN TRANSACTION increments @@TRANCOUNT by 1.

BEGIN TRANSACTION represents a point at which the data referenced by a connection is logically and physically consistent. If errors are encountered, all data modifications made after the BEGIN TRANSACTION can be rolled back to return the data to this known state of consistency. Each transaction lasts until either it completes without errors and COMMIT TRANSACTION is issued to make the modifications a permanent part of the database, or errors are encountered and all modifications are erased with a ROLLBACK TRANSACTION statement.

Although BEGIN TRANSACTION starts a local transaction, it is not recorded in the transaction log until the application subsequently performs an action that must be recorded in the log, such as executing an INSERT, UPDATE, or DELETE statement.

Naming multiple transactions in a series of nested transactions with a transaction name has little effect on the transaction. Only the first (outermost) transaction name is registered with the system. A rollback to any other name (other than a valid save point name) generates an error. None of the statements executed before the rollback is, in fact, rolled back at the time this error occurs. The statements are rolled back only when the outer transaction is rolled back.

BEGIN TRY
	BEGIN TRANSACTION
	
	DELETE	FROM HumanResources.JobCandidate
	WHERE	JobCandidateID = 13
	
	COMMIT
	
END TRY
BEGIN CATCH
	ROLLBACK
	
END CATCH

Hope this helps you in future when using transactions. If you are doing INSERTS, UPDATES and DELETES it is advisable that you use a transaction.

Execute SFTP Task in SSIS

Sometimes you need to automate the upload of a file to an FTP or SFTP. Thought I would share the way that I use the SFTP task in SSIS to upload files.

Firstly create the variables to use in the SFTP task. Variables are an easier way to manage things without going into the task, so you can change the password in the variable and not have to open up the SFTP task.

Next you need to complete the SFTP Task Editor.

What you need to take note of above that is very important is that you must remember to place the Remote File name. So this would be the name of the file you are uploading. Once the above is filled in you can click ok and your SFTP task should be ready to go without any red cross on it.

Example:
My ETL consists of generating a file to upload, then uploading the file and then sending a mail to notify users the files have been uploaded.

Hope this helps you with using the SFTP task in SSIS.

 

MDS 2016 Permissions Setup

Following on from a previous post of how to set up Master Data Services (MDS) with IIS, this post is about setting up permissions in MDS 2016.

In previous releases, you had to choose a Windows account during the installation and configuration of the MDS database. This account would become a system-wide administrator and have access to all models. The problem is sometimes system administrators chose their own account instead of a service account. If that person leaves the company, it could break the MDS installation if the account becomes invalid. Correcting this was not easy; it requires lots of manual changes in the MDS database. In SQL Server 2016, you still have to configure such an account.

However, you can now assign users to a new role called Super User. Users assigned to this role will have administrator access to all models. This allows is to mitigate the problem with the super user assigned during configuration of MDS. Furthermore, it also allows you to create multiple super users, which can be useful when maintenance is done by a team of administrators. You can assign users to this role in the Functions tab in the editing screen of a user in the User and Group Permissions section of MDS.

Aside from the Super User Role, some permission sets have been explicitly defined. For example, when a user had update permission on a model in a previous release – and no other permissions in the subtree below the model – the user would become a model administrator. However, if at a later point in time the user gets another explicit permission assigned in the model sub tree (for example on an entity), the user would lose model administrator permissions. Now you can explicitly assign the model administrator role to a user. Any permissions assigned on a lower level are ignored.

The same is true for entity administrators: you can now assign explicit entity administrator privileges to a user.

To recap, there are three administrator roles:

  • Super User – Access to all models and functional areas.
  • Model Administrator – If has access to explorer, the user can modify all master data. If access to system administration, the user can perform all administrative tasks on the model.
  • Entity Administrator – If has access to explorer, the user can modify all data of the entity. The user can also approve or reject change sets for the entity.

Note that making a user a Model Administrator on all the models is not the same as having the Super User permissions. A Super User has access to all the functional areas, while a Model Administrator needs explicit access to a functional area. For example, if a Model Administrator doesn’t have access to the System Administration functional area, he/she cannot create new entities.

In previous versions, you could only assign two permissions on a model object: read-only or update. With MDS 2016, you can now assign the following permissions: readcreateupdatedelete or deny.

If you want to assign a user all permissions (read + create + update + delete) you can choose the shortcut for All permissions. In the tree view, indicators are used to show which permissions a user has for an entity. On the right, you can view a summary of all permissions.

If you assign a user create, update or delete to an entity, the user automatically gets the read permission assigned as well.

Original Article here.

Using a ZIP Task in SSIS

The ZIP file task is a great feature that SSIS has for when you need to move/email a large amount of data. Also if you have multiple files you want to move to the same location, this makes it easier for you, so you can move just one file instead of many.

I prefer to use variables which I can change if the location changes over using hard-coded values. The first step is to create the variables on the package:

Next step is to place the Zip task in your Control Flow area. Then configure it as follows:

This will then compress and zip your files in the source you set. You can then use a Process System task to move this file to where you require it or use an email task to email the file to people.

Setting an Alert on a Stored Procedure

Recently I came across an issue where I needed to set an alert that when a report is populated it needs to send out an alert. Unfortunately in SSRS you can only do subscriptions and I have not found a way to do those kinds of alerts on an SSRS report.

A workaround I found for this was to set an alert on the stored procedure the report is using. (Hoping you are using stored procedures for SSRS reports and not a large query in the report dataset) You can do this by applying the IF statement with the Execute dbmail proc. See below:

CREATE PROCEDURE dbo.DepartmentAlert
AS
SELECT *
FROM HumanResources.EmployeeDepartmentHistory

--If there are more than or equal to 1 record pulled back it will fire the email.	
IF
(
	SELECT	COUNT(*)
	FROM HumanResources.EmployeeDepartmentHistory
) >= 1
BEGIN
	EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Alerting'
								,@recipients = 'jeanne.c17@gmail.com'
								,@body = 'Department history available'
								,@subject = 'Department History Availability'
								,@body_format = 'HTML'
	;
END
;

Next I created an SSIS package that uses a SQL execute task to execute my Stored Procedure. Then scheduled this to run every few hours and when it meets the IF statement validity then the mail is sent out to alert whoever is in the @recipients list.

Hope this helps you as much as it helped me.

Run a PowerShell Script from SSIS

It can be confusing to know which tool in the SSIS toolbox to use when trying to execute a PowerShell script from within SSIS.

The best task to use is an Execute Process Task. Under General you can give it a name and a description.

On the process section you fill in all the necessary details. Such as Executable, Arguments and Working Directory.

Once this is complete you can then execute your PowerShell script from within SSIS.

SSIS Save to XML Output

There isn’t much online about saving an output of data to an XML file. When trying with a file system task it throws errors. There is a workaround for this.

You can use a data flow task in SSIS to export to a flat file that is an XML file. You simply need to have a query that outputs in XML format, for example you can execute a stored procedure that returns the data in XML format:

SELECT [<?xml version="1.0"?> <batch>] = X.XMLString
FROM
(
SELECT XMLString = '<Messages xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.net/Wonga.Payments.Csapi.Commands"><CreateTransaction><ApplicationGuid>' + CONVERT(VARCHAR(36), ApplicationID) + '</ApplicationGuid><PostedOn>' + CONVERT(VARCHAR(19), X.EffectiveDate, 126) + '</PostedOn><Scope>' + CASE
WHEN AmountToPost < 0 THEN '2'
WHEN AmountToPost > 0 THEN '1'
ELSE '0'
END + '</Scope><Type>' + '18' + '</Type><Amount>' + CONVERT(VARCHAR(10), AmountToPost) + '</Amount><Mir>' + '0' + '</Mir><Currency>710</Currency><Reference>' + Reference + '</Reference><SalesforceUsername>User</SalesforceUsername></CreateTransaction></Messages>'
FROM
(
SELECT *
FROM #DataSet
) X
UNION
SELECT '</batch>'
) X
ORDER BY CASE
WHEN X.XMLString LIKE '<?%' THEN 1
WHEN X.XMLString LIKE '<M%' THEN 2
ELSE 3
END

EXEC dbo.GenerateXML WITH RESULT SETS
((
[<?xml version="1.0"?> <batch>] VARCHAR(MAX)
))

You use the Execute XML as the source from the database and then you use a flat file as your destination with .xml as the extension.

This should solve your problem of outputting to an XML file.