Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Data Management

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Your profile

    Search

    XML Feeds

    Google Ads

    « Can't depend on sp_depends? Try using sp_refreshsqlmoduleNot a fan of the Report Manager in SSRS? Using SSRS procedures to get the job done »
    comments

    SQLCLR adds a great deal to the SQL Developer list of methods to get the job done. That is pretty much a given. Hardware, resource usage and all that endless discussion aside, SQLCLR given handled correctly and given the hardware to utilize its abilities without putting memory and other pressure on your instances can be truly a beneficial aspect to your bag of tricks.

    As a DBA I have dozens of SQLCLR procedures that make my life unbelievably easier than in prior years. Also coming from years of developer experience have helped me along in catching on the SQLCLR. Today I thought sharing a few common and very useful DBA procedures would make a handy post.

    The first is DateTime formatting. Yesterday I posted on SSRS internal procedures In that post I gave up a handy SQLCLR procedure for formatting a DateTime value to handle Time Zone Offset. I use this one often in DBA tasks and draw off of it for many things.

    Here is that method again (this is also a UDF and not a Proc)

    1. public partial class UserDefinedFunctions
    2. {
    3.     [Microsoft.SqlServer.Server.SqlFunction]
    4.     public static SqlString DateTimeTimeZoneOffset(DateTime datetime_sent)
    5.     {
    6.         return new SqlString(datetime_sent.ToString("yyyy-MM-ddTHH:mm:ss.fffzzzz"));
    7.     }
    8. };

    Call

    1. Select dbo.DateTimeTimeZoneOffset('2009-06-26')

    Usage of this is seen directly in the blog post from yesterday and how it can be a simply task for formatting things like DateTime. Don't let it stop there though. Formatting strings for file names, headers, logs and on can be done quickly and easily with C# (or VB.NET) and makes this a great tool to any DBA.

    Next goes into file operations.

    The first is file movement. This can be done with external objects like batch, ActiveX scripts and even executables called via the OS command in jobs. Using this as a SQLCLR procedure makes it nice in calling the operation directly from the TSQL task you are performing though.

    Move file (which is also the rename file method)

    1. public partial class StoredProcedures
    2. {
    3.     [Microsoft.SqlServer.Server.SqlProcedure]
    4.     public static void MoveFile(string sfilename, string dfilename)
    5.     {
    6.         try
    7.         {
    8.             File.Move(sfilename, dfilename);
    9.         }
    10.         catch (Exception ex)
    11.         {
    12.             SqlContext.Pipe.Send("Error writing to file : " + ex.Message);
    13.         }
    14.     }
    15. };

    Call

    1. Exec MoveFile 'C:\txt_doc.txt','C:\txt_doc_new.txt'

    Write file

    1. public class SQLCLRIO
    2. {
    3.  
    4.     public static void WriteToFile(String content, String filename)
    5.     {
    6.         try
    7.         {
    8.             File.WriteAllText(filename, content);
    9.         }
    10.         catch (Exception ex)
    11.         {
    12.             SqlContext.Pipe.Send("Error writing to file : " + ex.Message);
    13.         }
    14.     }
    15. }

    Call

    1. Exec WriteToFile 'Testing....','C:\txt_doc_new.txt'

    Last one I'll post today is removing old files (backups typically) which is similar to a task I used to do using vbs scripts. The vbs scripts are a good method. I still use it on a few instances I want security more restricted as well. I say that of course as the permission level of any file operations SQLCLR will be external or unsafe. Given that setting is permitted in the situation, the SQLCLR is handy and easier to throw logging and other methods into the process.

    Delete old backups in a series of subdirectories.

    1. public partial class StoredProcedures
    2. {
    3.     [Microsoft.SqlServer.Server.SqlProcedure]
    4.     public static void RemoveOldBackups(string path,int retention)
    5.     {
    6.       try
    7.             {
    8.             DirectoryInfo dirList = new DirectoryInfo(path);
    9.             DirectoryInfo[] subs;
    10.             System.TimeSpan diff;
    11.  
    12.             subs = dirList.GetDirectories();
    13.  
    14.             foreach (DirectoryInfo dir in subs)
    15.             {
    16.                 foreach (FileInfo file in dir.GetFiles())
    17.                 {
    18.                     diff = DateTime.Now.Subtract(file.LastWriteTime);
    19.                     if (diff.Hours > retention)
    20.                     {
    21.                         file.Delete();
    22.                     }
    23.                 }
    24.             }
    25.         }
    26.         catch (Exception ex)
    27.         {
    28.             SqlContext.Pipe.Send("Error deleting from diretory : " + ex.Message);
    29.         }
    30.     }
    31. };

    Call

    1. Exec RemoveOldBackups 'C:\test\',23

    Have fun and don't forget the pressure SQLCLR can bring to you instances.



    *** If you have a SQL related question try our Microsoft SQL Server Programming forum or our Microsoft SQL Server Admin forum

    About the Author

    Ted Krueger is a SQL Server MVP and has been working in development and database administration for 13+ years. Specialties range from High Availability and Disaster / Recovery setup and testing methods down to custom assembly development for SQL Server Reporting Services. Ted blogs and is also one of the founders of LessThanDot.com technology community. Some of the articles focused on are Backup / Recovery, Security, SSIS and working on SQL Server and using all of the SQL Server features available to create stable and scalable database services. @onpnt
    Social SitingsTwitterLinkedInLTD RSS Feed
    1676 views
    Instapaper

    No feedback yet

    Leave a comment


    Your email address will not be revealed on this site.

    Your URL will be displayed.
    (Line breaks become <br />)
    (Name, email & website)
    (Allow users to contact you through a message form (your email will not be revealed.)