JSON In SQL Server

Facebooktwitterredditpinterestlinkedinmail

Finally in SQL Server 2016, Microsoft SQL Server now supports JSON serialization. It provides it through the FOR clause… like XML serialization. This will take a recordset and output it in JSON format with very little effort by the coder.

SELECT	AnimalID,
AnimalName,
Color
FROM	Animal
FOR	JSON PATH

As you can see. To get the output to come in JSON format, all you need to do is add FOR JSON PATH at the end of your query. Simple right? Here is what the results would look like.

[
	{
		"AnimalID":1,
		"AnimalName":"Dog",
		"Color":"Brown"
	},
	{
		"AnimalID":2,
		"AnimalName":"Flamingo",
		"Color":"Pink"
	},
	{
		"AnimalID":3,
		"AnimalName":"Polar Bear",
		"Color":"White"
	}
]

Adding All Columns In A Table To A Query [Easy]

Facebooktwitterredditpinterestlinkedinmail

I wanted to share this quick tip with you on how to add a list of all the columns in a table to your query window in SQL Server Management Studio. This is the easiest way I know!

  1. Expand the Object Explorer to show the table that you want to add the columns for.
        Adding All Columns 1
  2. Select the Columns folder on to your query window.
        Adding All Columns 2
  3. Drag the whole folder on to your query window and just drop it where you want it. That’s it!
    Adding All Columns 3

Delayed Transaction Durability

Facebooktwitterredditpinterestlinkedinmail

Starting with SQL Server 2014, they added a feature called delayed transaction durability. This is a very interesting concept that could give you some speed improvements in your database. In this post, I will try to explain what this feature is and what some advantages/drawbacks are.

 
Transaction Log Durability
In 2014, SQL Server gives us the ability to control how the transaction log files are written to the disk. It gives us 2 options. Full transaction durability and Delayed transaction durability.

  • Full Transaction Durability – This is the default level. This means that as soon as a SQL transaction is executed, the transaction log is written to disk BEFORE control is sent back to the client/user.
  • Delayed Transaction Durability – This setting means that the SQL transactions will be written to a memory buffer instead of the disk. The control is then sent back to the client/user after writing to the memory buffer.

 
Advantages
The delayed transaction durability has a few distinct advantage over full transaction durability.

The first advantage is that it doesn’t need to write to disk before giving control back to the client. In many databases, writing to the disk provides a lot of contention. Log file writes to the disk can sometimes slow queries down quite a bit. Writing to memory is much faster and should speed up your queries in general if your IO to the disk is slow.

Another advantage is that the delayed transaction durability buffers the writes to disk. SQL Server can get optimizations by buffering the write operations. Instead of writing each transaction to the disk, it will fill a buffer and then flush that buffer all at once.

 
Disadvantages
Everything up to this point sounds great, right? Delayed transaction durability comes with one major pitfall. Delayed transaction durability could cause data loss if SQL Server crashes. The data that isn’t written to disk can be lost if SQL crashes.

When Should I Use Delayed Transaction Durability?
Only use delayed transaction durability if you can afford some data loss if SQL Server crashes. If you cannot afford any data loss, do not use delayed transaction durability.

 
How To Turn On/Off Delayed Transaction Durability
Okay, now that you’re an expert on delayed transaction durability, let’s quickly cover the 3 levels of transaction durability and how to activate them.

There are 3 kinds of transaction durability. Disabled, Allowed, and Forced.
DISABLED – This means delayed transaction durability is turned off. All transaction writes will go to disk and there will be no potential for loss.
FORCED – This means that delayed transaction durability is turned on for every query. All transaction writes will go to memory and there is a potential for data loss.
ALLOWED – This is kinda in the middle. It basically means that you can turn on the delayed transaction durability in the query or stored procedure.

You will configure the durability with one of these statements:

ALTER DATABASE zoobase SET DELAYED_DURABILITY = DISABLED

GO

ALTER DATABASE zoobase SET DELAYED_DURABILITY = FORCED

GO

ALTER DATABASE zoobase SET DELAYED_DURABILITY = ALLOWED

If you use ALLOWED, you will need to add this hint to your commit transaction in in your sql query or stored procedure to activate the delayed transaction durability for it:

BEGIN TRAN

UPDATE	Animal
SET		AnimalName = 'Cow'
WHERE	AnimalName = 'Cattle'

COMMIT TRAN WITH (DELAYED_DURABILITY = ON)

 
 
Reference: https://msdn.microsoft.com/en-us/library/dn449490.aspx

 
 
NOTE: SQL Server shutdown/reboots are handled the same way as a crash. Make sure you flush your transaction buffer before rebooting!

Parsing A Delimited String In SQL Server

Facebooktwitterredditpinterestlinkedinmail

At some point in your life, you’ve probably had to parse a string inside SQL Server. Maybe you had a comma delimited string and you need the data inside a table. So, you go to stackoverflow and find some stored procedure that someone made that you don’t understand. It works, but yuck. Well… those days are over! In SQL 20016 they introduced a new table-valued function called STRING_SPLIT. This makes is very easy to parse a comma delimited string in SQL Server.

 
STRING_SPLIT Basics
The STRING_SPLIT function is really easy to use. It basically just takes 2 parameters. The first parameter is the string that you want to parse. The second parameter is the delimiter for parsing on.

The STRING_SPLIT function will always return a one column result set with a column named value.

Here’s an example of how to use it:

SELECT	value AS AnimalName
FROM	STRING_SPLIT('Dog,Cat,Bird,Walrus', ',')

[table width=”150″ colwidth=”150″ colalign=”left”]
value
Dog
Cat
Bird
Walrus
[/table]

 
If your input string has spaces by the delimiter, you just need to trim the value that you get from the function. Here’s an example of trimming the spaces and also parsing on a pipe character:

SELECT	value AS AnimalName
FROM	STRING_SPLIT('Dog |Cat |Bird | Walrus', '|')

 
 
Source: https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql

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.