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.

Requires A Singleton?

Facebooktwitterredditpinterestlinkedinmail

Have you ever got this error message when you tried to parse an XML string in SQL Server?

XQuery [value()]: ‘value()’ requires a singleton (or empty sequence), found operand of type ‘xdt:untypedAtomic *’

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 proc
SET		@XMLToParse =	'
								Baboon
						 '

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

 
How do we fix this?

This error is saying that the value() function needs an xpath that only exits once (non-repeating node). You and I know that there will only be one instance of , but SQL Server does not know that. To solve this, we just need to tell SQL Server that it should use the first instance of this AnimalName node that it finds. We do this by added the [1] tag to the xpath. We want to add it after the closing parentheses. This will tell SQL Server to grab whatever is the first node with that name.

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 proc
SET		@XMLToParse =	'
								Baboon
						 '

SELECT	
@XMLToParse.value('data(/Animal/AnimalName)[1]', 'VARCHAR(MAX)') AS AnimalName
-- Notice the [1] on the line above!

 
Extra Fun

If there are multiple nodes with the same name in your XML, you can adjust the number inside the square braces to match whatever node you want. For example:


	Baboon
	Cat
	Dog 

[1] would return Baboon
[2] would return Cat
[3] would return Dog

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

If Statement In An Update

Facebooktwitterredditpinterestlinkedinmail

If you are updating multiple rows in one statement, but only want to update a value in a column if a condition is satisfied, then you need to perform some sort of if logic inside your update. Here’s a straight forward way of doing this.

In the example below, I am just going to use 2 temp table variables. I’ll update the @SourceTable with the data from the @UpdateTable… but only where the UpdateFlag field is set to 1.

DECLARE @SourceTable TABLE
(AnimalID INT,
 AnimalName VARCHAR(255))
 
DECLARE @UpdateTable TABLE
(AnimalID INT,
 UpdateToValue VARCHAR(255),
 UpdateFlag  BIT)
 
INSERT
INTO   @SourceTable
VALUES (1, 'Dog'),
       (2, 'Cat'),
       (3, 'Snake')
 
INSERT
INTO    @UpdateTable
VALUES  (1, 'Pig', 1),
        (2, 'Cow', 0),
        (3, 'Turkey', 1)

UPDATE  S
SET     S.AnimalName =	CASE WHEN U.UpdateFlag = 1 THEN U.UpdateToValue 
							 ELSE S.AnimalName 
						END
FROM    @SourceTable S
INNER   JOIN @UpdateTable U ON U.AnimalID = S.AnimalID

SELECT *
FROM   @SourceTable S

 
In the example above, you can see that the AnimalName is only updated when the UpdateFlag column is set to 1. The 2nd record “Cat” is not updated with the value “Cow” because it has a 0 for the UpdateFlag. This is done using a case statement on the SET operation. The example above is very simple. This case logic in the SET operation becomes much more helpful in more complex queries.