Monday 28 August 2017

Retrieving binary data from base64 node in xml variable

In case there is xml document with base64 encoded binary data e.g. PDF (below example has the binary data shortened)

declare @doc xml
set @doc = '<doc><PdfData>JVBERi0xLjQN</PdfData></doc>'
then there is very simple to get the binary data decoded as binary again
select CAST (@doc.value('(//PdfData/text())[1]', 'varbinary(max)') AS varchar(max))

https://stackoverflow.com/questions/5082345/base64-encoding-in-sql-server-2005-t-sql

Friday 5 May 2017

How to find size of databases and last time they got accessed

Sometimes you may need to free some space on MSSQL server and idetify databases which are not used long time back. This is especially useful on development servers where people may restore database just for troubleshooting of some issues and then the database is not needed anymore!

with fs
as
(
    select database_id, type, size * 8.0 / 1024 size
    from sys.master_files
)

select db.*, last_user_seek = MAX(last_user_seek),
 last_user_scan = MAX(last_user_scan),
 last_user_lookup = MAX(last_user_lookup),
 last_user_update = MAX(last_user_update)
from (
 select 
  name,
  (select sum(size) from fs where type = 0 and fs.database_id = db.database_id) DataFileSizeMB,
  (select sum(size) from fs where type = 1 and fs.database_id = db.database_id) LogFileSizeMB 
 from sys.databases db
) as db
left join sys.dm_db_index_usage_stats stats on stats.database_id = db_id(db.name)
group by db.name, db.DataFileSizeMB, db.LogFileSizeMB
order by db.DataFileSizeMB desc

References:
Sql server 2008 howto query all databases sizes
How do you find the last time a database was accessed