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"
	}
]

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.

SQL Server Replace

Facebooktwitterredditpinterestlinkedinmail

Replacing text in SQL Server is easy. SQL Server has the REPLACE function to perform this task.

SQL Server REPLACE
The REPLACE function in SQL Server has 3 parameters.

  1. Text to search
  2. Text to find
  3. Text to replace with
SELECT	REPLACE('Full text to search in', 'search', 'replace') AS ReplacedText

The output is: Full text to replace in

In the above example, we are searching “Text to search in” for the word “search” and we are replacing it with the word “replace”. Pretty simple, right? Now let’s take it a step further.

SQL Server Case Sensitive Replace
Above we went over how to do a case insensitive replace on a string. (The REPLACE function actually uses the default collation of the input text that it is searching). To turn it in to a SQL Server case sensitive replace, we just need to add one small thing to the end. We need to change the collation of the text we are searching. Learn more about text collation here.

SELECT REPLACE('Full text to search in' COLLATE SQL_Latin1_General_CP1_CS_AS, 'SEARCH', 'replace') AS ReplacedText

The output is: Full text to search in

This example shows how the “SEARCH” text was not found because we are changing the input text to search collation to SQL_Latin1_General_CP1_CS_AS (which is case sensitive). The input string has “search” in lower case and we were searching for an upper case “SEARCH”.

 
Reference: http://msdn.microsoft.com/en-us/library/ms186862(v=sql.120).aspx

SQL Server Zero Pad Left

Facebooktwitterredditpinterestlinkedinmail

In a recent project, I had the task of padding a number with zeros. SQL Server doesn’t have a built in Zero Pad Left function. SQL Server does have a Right function. You can use this to create a zero padded left string.

SELECT	RIGHT('0000000000' + @TextToZeroPad, 10) AS ZeroPaddedText

In the code above, I am take 10 zeros, appending a text value to it, then taking the right 10 characters. The end result is the same as padding the left with zeros.

 
SQL Server Zero Pad Left Function
You can take this a step further and create a scalar function out of it.

CREATE	FUNCTION PadLeft
		(@TextToPad 	 	VARCHAR(8000),
		 @CharacterToPad	VARCHAR(1),
		 @NumberToPad	 	INT)
RETURNS		VARCHAR(8000)
AS
BEGIN
	DECLARE	@OutputText VARCHAR(8000)
	
	-- Create a string with the maximum number of padded characters followed
	-- by the text that we want to pad
	SET		@OutputText = REPLICATE(@CharacterToPad, @NumberToPad) + @TextToPad
	
	-- Take the right X characters to simulate the padding
	RETURN	RIGHT(@OutputText, @NumberToPad)
END

SQL Server Truncate Date

Facebooktwitterredditpinterestlinkedinmail

A common function that people need to do when dealing with datetimes is extracting the date from the datetime.  Oracle has a built-in function to do this called TRUNC.  SQL Server does not have this (yet).  However… you can accomplish this very easily.  Here are a few ways to perform a truncate date function in SQL Server.

-- Assign date to variable
DECLARE	@DateToTruncate	DATETIME = '2014-08-01 14:12:34'

-- Get the date using casts
SELECT	CAST(CAST(@DateToTruncate AS DATE) AS DATETIME)

-- Get the date using convert
SELECT	CAST(CONVERT(VARCHAR(10), @DateToTruncate, 101) AS DATETIME)