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.

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

How To Pull Single Value From XML

Facebooktwitterredditpinterestlinkedinmail

SQL Server has a built in method for easily pulling one value from an XML. To do this you use the method called .value(). The .value method will run an XQuery against the XML specified in the query. This method is scalar, so it will only return 1 value. You cannot use this to return multiple values.

DECLARE	@XMLToParse  XML
 
-- Load the XML data in to a variable to work with.
-- This would typically be passed as a parameter to a stored procedure
SET	@XMLToParse =	'
						Baboon
					 '

SELECT  @XMLToParse.value('data(/Animal/AnimalName)[1]',
							'VARCHAR(MAX)') AS AnimalName

In the query above, you can see that you can just pass the xpath and the datatype that you want the output to be. This will pull that value out of the XML and put it in the specified format. You can see that after the xpath, there is a funny syntax [1]. This tells SQL Server to grab the first instance of the AnimalName node. You need to do this because the .value() method only returns one value and will not work with a repeating node.

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

Cross Apply In SQL

Facebooktwitterredditpinterestlinkedinmail

CROSS APPLY is one of those helpful things in SQL Server that most people don’t think of or may not even know about. In this article I’d like to talk about what the APPLY operator is and how we can use it to simplify our sql statements.

APPLY Operator
The APPLY operator allows you to join a table to a table-valued function. A table-valued function is a function that will return a table with one or more columns. With the apply operator, you can pass values from the first table in to the table-valued function.

There are only 2 types of APPLY operators:
CROSS APPLY – Returns records when a value from both sides of the operator match. Like an INNER JOIN.
OUTER APPLY – Returns all rows from the other side of the operator and will return the value or NULL from the table-valued function. This is like an OUTER JOIN.

SELECT	A.AnimalName,
		H.HabitatName
FROM	Animal A
CROSS	APPLY GetAnimalHabitat(A.AnimalTypeCode) H

In the example above, you can see that we join to the GetAnimalHabitat function using the CROSS APPLY. You can imagine that this function does a bunch of logic that is not visible in this query. If the GetAnimalHabitat function had 25 lines of code, you can see how this simplifies the above query dramatically.

Additional Thoughts
The APPLY operator can simplify the code, but could be accomplished by joining to a sub query as well. One difference is that the function in the APPLY operator is being executed for every row in the outer table. If you use the APPLY operator, make sure that you test the speed of your query to make sure that it did not degrade performance.