Showing posts with label SQL CLR. Show all posts
Showing posts with label SQL CLR. Show all posts

Friday, May 9, 2008

Using a CLR TVF to SELECT from the SQL Error Log

One of the things I have always wanted to do, but have never been able to easily is to select from the ErrorLogs as if they were tables. To do this in the past has always required creating a temp table, inserting the results of the xp_readerrorlog or sp_readerrorlog into it, and then selecting out of that table. By using a CLR TVF with EXTERNAL_ACCESS, you can easily be able to select from the ErrorLogs as if they were actual tables in a simple statement.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
 
/*=========================================================================================

  File:      fn_ReadErrorLog.cs
  Summary:   Table-valued function to retrieve the SQL Server Error Log for the
             current instance as a table.
  Parameter: LogNumber - The Log Number in the ErrorLogs to Read.
             Specify NULL or 0 to refer to active log
  Date:      May 9, 2008

---------------------------------------------------------------------
 
THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.

============================================================================================ */

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction(Name="fn_ReadErrorLog", 
        FillRowMethodName = "FillRowErrorLogReader", 
        DataAccess = DataAccessKind.Read, 
        TableDefinition = "LogDate datetime, ProcessInfo nvarchar(100), Text nvarchar(4000)")]
    public static IEnumerable InitMethodErrorLogReader(int LogNumber)
    {
        List<string[]> logitems = new List<string[]>();
 
        string servername;
        using (SqlConnection conn = new SqlConnection("context connection=true"))
        {
            conn.Open();
            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = "select serverproperty('ServerName')";
                servername = (string)cmd.ExecuteScalar();
            }
            conn.Close();
        }
 
        using (SqlConnection connection = new SqlConnection("Server=" + servername + ";Integrated Security=true"))
        {
            connection.Open();
            SqlCommand sqlCommand = connection.CreateCommand();
            sqlCommand.CommandText = "exec xp_readerrorlog " +LogNumber.ToString();
            SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();

            while (sqlDataReader.Read())
            {
                string[] item = new string[3];
                item.SetValue(sqlDataReader["LogDate"].ToString(), 0);
                item.SetValue(sqlDataReader["ProcessInfo"].ToString(), 1);
                item.SetValue(sqlDataReader["Text"].ToString(), 2);
                logitems.Add(item);
            }
        }
        return logitems;
    }

    public static void FillRowErrorLogReader(object obj, out SqlDateTime logDate,
        out SqlString processInfo, out SqlString text)
    {
        string[] item = (string[])obj;
        logDate = (SqlDateTime)DateTime.Parse(item[0].ToString());
        processInfo = (SqlString)item[1].ToString();
        text = (SqlString)item[2].ToString();
    }
};


This Example will also be posted on SQLCLR.net in the coming days.

Friday, April 4, 2008

SQLCLR.net Site Online

I finally got the issues with http://www.sqlclr.net resolved with the hosting company, and the site is online and ready to accept submissions from registered users. I am spending alot of time learning the DotNetNuke platform, and configuring the site for access, but I have been able to post a few articles, and examples on the site:

Enabling CLR in SQL Server

Generic Regular Expression Function

I am also seeking content from other users on the internet that I find, by email. Hopefully I can bolster up support for this site and get it off the ground.

Thursday, April 3, 2008

SQLCLR.net Site Creation

I find that as time progresses, more and more people are starting to use CLR in SQL Server, and that is good, but the online resources for CLR in SQL are sparse and sometimes impossible to find without hours of searching depending on the problem at hand. I have registered SQLCLR.net and created a site, but am currently having some issues with my hosting and ASP.NET that are delaying the launch. Interestingly enough, someone has registered SQLCLR.com already, but there is just a link to their blog site. Hopefully this isn't a duplicated effort.

Sunday, March 30, 2008

CLR Approved Assemblies

A little known fact about using CLR integration in SQL Server is that not all of the .NET Assemblies are available for use.

Supported .NET Framework Libraries

This means that in order to use components of the .NET Framework that are not supported, you have to first create them as a, generally UNSAFE, Assembly in the database. This however can lead to support issues with Microsoft Support, according to their KB Article

Bob Beauchemin covered this in a recent blog after upgrading .NET on a SQL 2005 Server. If you choose to reference an unsupported Assembly in your CLR code, your Assembly will cease to function and execution will result in an exception with Message 622 and an error ending with:

Assembly in host store has a different signature than assembly in GAC.

To correct, you must drop your assembly as well as the unsupported assemblies, and add them back so the GAC is refreshed with the newer version.

Thursday, March 6, 2008

CLR Safety Issues After Database Restore to New Server

This post has been migrated to my new blog on SQLBlog.com. You can find this post at the following address:

http://sqlblog.com/blogs/jonathan_kehayias/archive/2008/03/06/clr-safety-issues-after-database-restore-to-new-server.aspx