SQL Server Kill All Connections

Facebooktwitterredditpinterestlinkedinmail

Killing all connections in SQL Server is something that you may need to do from time to time. The two times that I’ve needed to do this most is when I’m restoring a database in my test environment or when I need to rename a database. Both of these operations require that there are not any open connections to the SQL Server database. There are a couple good scripts that I will show here. My favored method is to set it in single user mode.

 
Kill All Connections Using Single User Mode
This is the easiest way kill all the connections to the database. It basically sets the database to only allow 1 user (you) and it will kill all the other connections.

-- Kill all connections and set to single user mode
USE	MASTER
GO
ALTER	DATABASE [DatabaseName] 
SET 	SINGLE_USER
WITH	ROLLBACK IMMEDIATE
GO

-- Do your operations

-- Set the database back in to multiple user mode
USE	MASTER
GO
ALTER	DATABASE [DatabaseName] 
SET 	MULTI_USER
GO

 
Kill All Connections Using The Kill Command
The following query will loop through all the open processes on the database and kill each one. Note that this may take a little bit of time to execute if there are long running transactions, it may take some time to roll them back.

USE	MASTER
GO

DECLARE	@Spid INT
DECLARE	@ExecSQL VARCHAR(255)

DECLARE	KillCursor CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
SELECT	DISTINCT SPID
FROM	MASTER..SysProcesses
WHERE	DBID = DB_ID('DatabaseName')

OPEN	KillCursor

-- Grab the first SPID
FETCH	NEXT
FROM	KillCursor
INTO	@Spid

WHILE	@@FETCH_STATUS = 0
	BEGIN
		SET		@ExecSQL = 'KILL ' + CAST(@Spid AS VARCHAR(50))

		EXEC	(@ExecSQL)

		-- Pull the next SPID
        FETCH	NEXT 
		FROM	KillCursor 
		INTO	@Spid  
	END

CLOSE	KillCursor

DEALLOCATE	KillCursor

 
Reference: https://msdn.microsoft.com/en-us/library/bb522682(v=sql.105).aspx
https://msdn.microsoft.com/en-us/library/ms173730.aspx

Compressing Data In SQL Server

Facebooktwitterredditpinterestlinkedinmail

In SQL Server 2016 they added a sweet new featured to allow you to compress input strings and binaries. The new COMPRESS function allows the field or literal value passed in to the function to be compressed in GZip format.

 
COMPRESS
The COMPRESS function will take in an input and compress it using a GZip compression. The output from the function is a VARBINARY datatype. You can display that in a SQL Server Management window or store it in a table with a VARBINARY(MAX) field. To use the COMPRESS function, you need to pass in either VARCHAR, BINARY, VARBINARY, or CHAR datatypes.

 
How To Use The COMPRESS Function
For this example, I’m going to put the data in to a table variable. If you have a permanent table structure, you can use that instead.

DECLARE	@InsertTest TABLE
	(AnimalName VARCHAR(50),
	 AnimalStats VARBINARY(MAX))

INSERT
INTO	@InsertTest
VALUES	('Dog', 
		 COMPRESS('Height: 26 inches; Weight: 20 pounds; Color: Brown'))

SELECT	*
FROM	@InsertTest

If you’re looking to compress some data just inside SQL Server Management Studio, you can just do this:

SELECT	COMPRESS('this is the data I want to compress') AS CompressedData

 
 
How To Decompress Your Data

So now that you’ve compressed data, how to do you decompress it? As you guessed, SQL Server also added a DECOMPRESS function. It’s just as simple as the COMPRESS function, just with one little twist. The DECOMPRESS function only returns the datatype VARBINARY(MAX). You will have to cast it in to whatever you want. Here’s an example using the same script as we used above:

DECLARE	@InsertTest TABLE
	(AnimalName VARCHAR(50),
	 AnimalStats VARBINARY(MAX))

INSERT
INTO	@InsertTest
VALUES	('Dog', 
		 COMPRESS('Height: 26 inches; Weight: 20 pounds; Color: Brown'))

SELECT	*
FROM	@InsertTest


SELECT	CAST(DECOMPRESS(AnimalStats) AS VARCHAR(250)) AS DecompressedAnimalStats
FROM	@InsertTest

You can see above that I just wrapped the DECOMPRESS function with a CAST function. It’s that simple to get it in the format that you want.

 
Something To Keep In Mind: Compressed data can’t be indexed! Sorry!

Something Else To Keep In Mind: If the goal is to compress all the data in a row/table/data page/or index, SQL Server (as of 2016) now supports this using a different built-in method. So you don’t have to do it all manually.

Get Filestream Storage Directory

Facebooktwitterredditpinterestlinkedinmail

Filestreams are a great way to store files in SQL Server. SQL Server makes this super easy by managing the storage of the physical files on the file system. But what if you want to get access to these files or if you want to know where they are stored. SQL Server wants you to access these files through a network share managed by SQL Server. They provide a function called PathName that you can call to get this path. You will call this function like you would call an extension method in .Net. In the example below, we will assume that the column InvoiceFile is a Filestream datatype. We call the PathName() function to get the share name to where the files are stored.

SELECT	TOP 1
		InvoiceFile.PathName() AS DirectoryOfFile
FROM	Invoice

Estimate Backup Size In SQL Server

Facebooktwitterredditpinterestlinkedinmail

When you’re creating your database backup maintenance plans, you need to choose a drive that has enough space for your backup. So how much space will you actually need to backup your database? Figuring this out is actually a lot easier than you would expect.

Although nothing will be 100% accurate, SQL Server has a built in stored procedure for calculating the used space in a database. A full database backup only stores the actual data/objects in the database. The unused space is not stored.

 
EXEC sp_spaceused @updateusage = N'TRUE'
 

In the example above we call the sp_spaceused stored procedure from the database that we would like the size from. This is important… you need to execute this from the database that you want to get the size for. This will return a dataset with multiple columns. The column that you will look at is the reserved column. This will show the amount of space without the unused space.

 
Note
The @updateusage parameter tells the stored procedure to update the space usage info before returning the used size. Passing TRUE in to this parameter will give us the most accurate size estimate.

SQL Server LIKE With Percent Literal

Facebooktwitterredditpinterestlinkedinmail

The LIKE operator in SQL Server is a really powerful tool. It allows you to specify a pattern to match records in your where clause. You can use the % (percent) as a wildcard value. For example: ‘monk%’ will match ‘monkey’ and ‘monkeys’. But what if you want to match the words ‘60% off sale’ and ‘60% off sales’… you can’t just put ‘60% off sale%’… you need to escape the first %. SQL Server gives us two different ways to escape a special character.

 
SQL Server LIKE – Exact Single Character

The first way that you can do this is by specifying a specific single character in your pattern. This is done by wrapping the single character in [ ]. The character that you put inside the brackets will tell the system that that character must be found exactly as appears.

SELECT	SaleDescription
FROM	SaleInfo
WHERE	SaleDescription LIKE '60[%] off sale%'

 
SQL Server LIKE – Escape Character (read at the bottom of this post to find out what an escape character is)

The second way that you can do this is by specifying an escape character. This is done by using the keyword ESCAPE after your pattern. The literal value of the wildcard character following the escape value will be used instead of the wildcard value. In the example below, we specify that ! is our ESCAPE character in our string. Then we put ! before %. That way the database will look for the literal value of % instead of using that in the wildcard pattern.

SELECT	SaleDescription
FROM	SaleInfo
WHERE	SaleDescription LIKE '60!% off sale%' ESCAPE '!'

 
What Is An Escape Character

An escape character is a character that is placed before a character (or string of characters) and it tells the system to read the following character as their literal value. Many systems have reserved characters that act as codes or wildcards in their system. Using an escape character, you tell the system to not read those values as special codes or wildcards.

 
Reference: https://msdn.microsoft.com/en-us/library/aa933232(v=sql.80).aspx