Tag Archives: t-sql

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: https://en.wikipedia.org/wiki/Null_device

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.

Output:

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

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

 

Get and Kill Executing Processes of Job

This query will identify the current SQL processes or executions which belong to a specific job.

We had a job process that was getting blocked for long periods, and in turn was causing a lot of blocking.  The best solution here is to fix the root blocker, however, as a short term fix we want to allow the job to run but then kill it a specific time if it is still running.  To do this, we create another job that looks for all of the SPIDS associated to executions which belong to the job getting blocked, and execute a kill commend for each SPID.

 

Show SP_Who and Rollback Status for All SPIDS Rolling Back

We had a session we had to kill and roll back and wanted some more information about the status of the roll back.  If you only have one SPID to check then you can run the kill commend with an option:

I wanted to expand this by dynamically looking for all sessions in rollback status and then provide some information about the session as well as the kill status.  This way, I do not need to first manually review sessions and look for records in rollback status, then check each kill status.

In my test there was only one SPID in rollback status but it will work if there are more than one.

List SQL Servers On Network

A list of servers can be obtained using windows command prompt (cmd) or powershell (ps).  CMD and PS both provide Server Name and Instance Name, however, powershell provides two additional fields: IsClustered, and SQL Server Version.  One challenge I have noticed is that running these commands from my local machine only returns a short list with names that look like computer names and not server names.  I had to run the commands from a production server, a QA server, and a development server to obtain the server lists from those environments.  There must be some network separation between them, which I am still investigating.

CMD: OSQL -L or SQLCMD -L

PS: [System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSources()

Check if SQL Server is Clustered

For more information on SERVERPROPERTY(): https://msdn.microsoft.com/en-us/library/ms174396.aspx

Random n% Records – Fastest Method

Method Source: https://msdn.microsoft.com/en-us/library/cc441928.aspx