CLR in SQL Server

According to Microsoft, Use Transact-SQL when the code will mostly perform data access with little or no procedural logic. Use managed code for CPU-intensive functions and procedures that feature complex logic, or when you want to make use of the BCL of the .NET Framework.

1. Create SQL Stored Procedure in visual stuido
Project name: “FirstSqlClass.cs”; class name:”FirstSqlClr” and function name:”ListEmployees”

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;   
 
 
public partial class FirstSqlClr
{
    [Microsoft.SqlServer.Server.SqlProcedure]
 
    public static void ListEmployees(SqlString fLetter, SqlString orderBy, out SqlString outputParameter)
    {
        string sqlCmd = "";
        sqlCmd += " select c.LastName, c.FirstName, c.EmailAddress ";
        sqlCmd += " from Person.Contact as c inner join HumanResources.Employee as e on c.ContactID = e.ContactID ";
        sqlCmd += " where left(c.LastName, 1) = @fLetter";
        sqlCmd += " order by " + orderBy.ToString();        
 
        SqlContext.Pipe.Send("Stored Procedure started at: " + DateTime.Now.ToString() + "\n");
        using (SqlConnection conn = new SqlConnection("context connection = true"))
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sqlCmd, conn);
            cmd.Parameters.Add(new SqlParameter ("@fLetter", SqlDbType.NVarChar, 1));
            cmd.Parameters[0].Value = fLetter;
 
            SqlDataReader rdr = cmd.ExecuteReader();
            SqlContext.Pipe.Send(rdr);
        }
        outputParameter = "after some manipulation that has to be done by a procedure language.";
        SqlContext.Pipe.Send("Stored Procedure ended at: " + DateTime.Now.ToString() + "\n");
    }    
};

2. Set Target Framework to “.Net 2.0” SQL 2008 only support .Net 2.0. Comply to DLL.
3. Enable Clr in Sql Server:

sp_configure 'clr enabled', 1
go
reconfigure
go

4. Register the assembly in SQL Server Locate the Dll file and set Permission to “SAFE”.

use AdventureWorks
go
create assembly FirstSqlClrClass from
'C:\Users\kwu\Documents\visual studio 2010\projects\FirstSqlClrClass\FirstSqlClrClass\bin\Debug\FirstSqlClrClass.dll'
go

5. Create Stored Procedure

use AdventureWorks
go
create procedure FirstListEmployees(@fLetter Nvarchar(1), @OrderBy NVarchar(20), @outputParameter NVarchar(100) OUT) as
external name FirstSqlClrClass.FirstSqlClr.ListEmployees
go

The the SP can be used as regular T-Sql stored procedure.

use AdventureWorks
go
DECLARE @return_value int,
@outputParameter nvarchar(100)

EXEC @return_value = [dbo].[FirstListEmployees]
@fLetter = 'B',
@OrderBy = 'EmailAddress',
@outputParameter = @outputParameter OUTPUT

SELECT @outputParameter as N'@outputParameter'

SQLCMD

SQLCMD was first introduced with SQL Server 2005 and was designed as a replacement to old SQL utilities like OSQL and ISQL. SQLCMD was written from scratch, and a lot of effect was put into performance and features. Before typing sql in Management Studio query editor, do not forget to enable SQLCMD mode under Query menu. It will pass the script to the SQLCMD application instead of submitting it to the database engine directly.
Unlike old tools,with use ODBC to connect to SQL Server, SQLCMD uses more efficient OLE DB connection and allows you to make multiple connections to different servers within the same script. SQLCMD also provides the ability to pass variables from either command line arguments or within the script itself.

Samples:

To backup DB you can use the following script:

:SETVAR myConnection FENCO-DW1
:SETVAR myDatabase AdventureWorks
 
BACKUP DATABASE $(myDatabase) TO DISK='C:\Backups\$(myDatabase).bak'
GO

the result:

Processed 21312 pages for database 'AdventureWorks', file 'AdventureWorks_Data' on file 1.
Processed 1 pages for database 'AdventureWorks', file 'AdventureWorks_Log' on file 1.
BACKUP DATABASE successfully processed 21313 pages in 3.590 seconds (46.381 MB/sec).

Essential SQL Server Date Time Functions

Returns a datetime value for the specified year, month and day

CREATE FUNCTION [dbo].[ReturnDate](@YEAR INT, @MONTH INT, @DAY INT) RETURNS datetime
AS
    BEGIN
    RETURN dateadd(MONTH,((@Year-1900)*12)+@Month-1,@Day-1)
    END

Returns @DateTime at midnight; i.e., it removes the time portion of a DateTime value.

CREATE  FUNCTION DateOnly(@DateTime DateTime)
RETURNS datetime
AS
    BEGIN
    RETURN dateadd(dd,0, datediff(dd,0,@DateTime))
    END

Sample:

SELECT dbo.ReturnDate(YEAR(getdate()), MONTH(getdate()),1) -- returns the first day of the current month.
SELECT dbo.ReturnDate(YEAR(getdate()), MONTH(getdate())+1,0) -- returns the last day of the current month.

Go to there for details:
http://weblogs.sqlteam.com/jeffs/archive/2007/01/02/56079.aspx