Category Archives: Databases

Backup Transaction Logs to Nul for All Online Databases

First of all, never use this in a production environment!   This script is to backup your transaction logs to a “nul device” for all online databases which are not using simple recovery model.  In windows it is indeed spelled “nul” with one “L”.  The only reason you would want to do this is if you have a non production environment using full recovery model and this server architecturally mirrors your production environment.  For example, we have a “staging” server that is used for testing our code changes before they go into production.  We require the staging environment to be as close to production as possible and have scheduled scripts that sync them weekly.  In this scenario, we have many databases in the staging server that are using full recovery model but we do not want to backup the t-logs, we would rather just throw them away.

To learn more about NUL devices, here’s a link to the wikipedia page:

Resolve SQL Server Fatal error: cannot create ‘R_TempDir’

I was trying to test an install of R in SQL Server 2016 and when running a script I received this error: Fatal error: cannot create ‘R_TempDir’

Following the instructions here, I enabled external scripts, restarted the sql server service, and then tried to run the following test script:

This is when the fatal error occurred.  As the error suggests, R is having some issues creating a temporary directory.  After some internet searching and trial and error I got past the issue.

Enable  8dot3 File Names

R configuration uses the 8dot3 file name convention, also known as “short names”.  To enable this on windows 10, run the following command in CMD (command prompt):

For more options and information look here:

Give access to the working directory to R

Locate and open “rlauncher.config” file in a text editor.  This file will be under the “<sqlserver_instance>\binn” directory.  Take a look at the location of WORKING_DIRECTORY.  This should have a “short name” file path.  The path should be something like “<sqlserver_instance>\EXTENS~1”, and “\EXTENS~1” is equivalent to “\ExtensibilityData”.  We need to give access to R to this folder. I did this by changing the permissions to full control to everyone.  You may want to be more restrictive here, but in my case this did not matter.

  • Right click folder > Properties > Security tab > Advanced > Add
  • Select a principal (I entered “Everyone”
  • Tick “Full control” under basic permissions and click “OK”
  • Tick “Replace all child object and permissions entries with inheritable permissions entries from this object” and click “OK”

Now if you rerun the script above you should get a result of “hello, 1”.

Collapse and Concatenate Rows

I had a need to concatenate  and comma separate some multi-row data into an array of values with each having an unknown number of elements, in other words, take a many to one parent-child relationship and collapse the many child rows into the one parent record and separate the child record values with a comma.  In the past, my default method to solve this problem was to build a temporary  table  and then use a loop to iterate through a data set and append the elements by updating rows in the temporary table, or use a common table expression with anchor and recursive members.  Recently I stumbled upon the “stuff” and “for xml” functions.  I had seen these functions  before but never took the time to understand their potential use.  These function can be used to solve the problem mentioned.

T-SQL For XML (Path Mode)

Function Description: A SELECT query returns results as a rowset. You can optionally retrieve formal results of a SQL query as XML by specifying the FOR XML clause in the query. The FOR XML clause can be used in top-level queries and in sub queries. The top-level FOR XML clause can be used only in the SELECT statement. In sub queries, FOR XML can be used in the INSERT, UPDATE, and DELETE statements. It can also be used in assignment statements.

In a FOR XML clause, you specify one of these modes: RAW, AUTO, EXPLICIT, PATH.  We will only use PATH for this exercise.

The PATH mode together with the nested FOR XML query capability provides the flexibility of the EXPLICIT mode in a simpler manner.

The EXPLICIT mode allows more control over the shape of the XML. You can mix attributes and elements at will in deciding the shape of the XML. It requires a specific format for the resulting rowset that is generated because of query execution. This rowset format is then mapped into XML shape. The power of EXPLICIT mode is to mix attributes and elements at will, create wrappers and nested complex properties, create space-separated values (for example, OrderID attribute may have a list of order ID values), and mixed contents.

I will not list the syntax for this function because it can get pretty complex very quickly for all of the options.  Instead, you can see in the example I just use it to concatenate the rows into a comma separated array.   Any other XML is basically ignored by passing  in the argument “Path (”)”.

(More information on For XML)

T-SQL Stuff Function

Function Description: The STUFF function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.

Function Syntax: STUFF ( character_expression , start , length ,character_expression )

(More Information on the Stuff function)

Example Problem

List database users and include all roles of which a user is a member, separated by comma.

Solution using Stuff and For XML

  • “For XML” is used to collapse and concatenate the row data into a single array.
  • “Stuff” is used to remove the leading comma.
  • Note that we are using a correlated subquery when we reference “dp.principal_id” in order to limit our roles and role members to our database principals in the main outer query.


principal_id type_desc create_date modify_date Roles
5 SQL_USER 11/13/2002 6/19/2010 db_owner
7 SQL_USER 11/13/2002 6/19/2010 db_owner,db_datareader,db_datawriter
8 WINDOWS_USER 3/26/2009 3/26/2009 db_datareader
10 WINDOWS_USER 3/16/2008 3/16/2008 db_datareader
11 SQL_USER 7/11/2008 6/19/2010 WebViews
13 SQL_USER 7/25/2014 7/25/2014 role_proxyusers
14 WINDOWS_USER 3/12/2009 3/12/2009 db_datareader
16 SQL_USER 7/25/2014 7/25/2014 role_proxyusers
18 SQL_USER 8/26/2005 6/19/2010 db_owner
19 WINDOWS_USER 6/2/2009 6/2/2009 MSReplPAL_9_1,db_datareader
20 WINDOWS_GROUP 10/3/2005 10/3/2005 db_datareader
21 SQL_USER 7/14/2009 5/2/2016 role_proxyusers,db_datareader,db_denydatawriter

Microsoft SQL Server Developer Edition is now free

“Exciting news! Starting today, SQL Server 2014 Developer Edition is now a free download for Visual Studio Dev Essentials members (you will be prompted to sign in to Visual Studio Dev Essentials before you can download SQL Server 2014 Developer Edition). We are making this change so that all developers can leverage the capabilities that SQL Server 2014 has to offer for their data solution, and this is another step in making SQL Server more accessible. SQL Server Developer Edition is for development and testing only, and not for production environments or for use with production data.”

“SQL Server 2016 Developer Edition, when released later this year, will also be free. To learn more about the exciting new features in SQL Server 2016, read the datasheet.”

Create Read Only User in Azure DB

I have been struggling with creating a user who has read only access to an azure database and finally figured it out.  The key is connecting to the right database in a new session when executing the t-sql commands.  This is because you can not execute a “use” statement, change the database in the current session via the GUI, and you can not make named references to databases in your t-sql.


Validate user has read only permissions by connecting to database using these new credentials and executing something like “CREATE TABLE dbo.test (test datetime);”, which should return an error message indicating permission denied.

More information on managing database access and login security in azure:

Get Database Sizes in PestgreSQL

Returns the database name, owner, and size on a given server.  Tested in PostgrSQL 9.2 and 9.3.


SQL Server Job to Capture Reads

We needed to capture physical reads over time from our SQL server.  One method we decided to deploy was to check sys.dm_exec_query_stats periodically and capture the differences between each check.  The way I am doing it below is not 100% accurate because sys.dm_exec_query_stats is based on cached plans and the server will let clear the plan data over time.  This means that when the differences are calculated any plan that was cleared from cache would not be included in the current check, but would still be in the comparison record.  This could be solved by storing and comparing at the plan level but for my purposes I prefer to store summary information and do not mind this issue because I am running my comparison every hour and then will be averaging the results over time, and the result does not need to be exactly precise, just close enough to give us a general understanding.

This is the query inside the job:

This is what the table looks like with a few records.  Note that this is a result of running the job multiple times with a few seconds between each interval.

SQL Server Job to Capture Reads result

Disable then Enable SQL Agent Jobs

This script has three actions:
1) Put Current Job Information Into Temp Table
2) DISABLE All SQL Server Agent Jobs
3) ENABLE SQL Server Agent Jobs Which Were Enabled Prior to Disabling
Note: If you need to disconnect from the server after step 1 then step 3 will not be able to read from the temp table. Instead, you would have to feed a list of job IDs to the query. I have created a place for this just in case this is what you have to do.

Test Results:
Put Current Job Information Into Temp Table: 47 row(s) affected
DISABLE All SQL Server Agent Jobs: 33 row(s) affected
ENABLE SQL Server Agent Jobs Which Were Enabled Prior to Disabling: 33 row(s) affected