We have done very excitement stuffs in ADO.NET 1.0 now ADO.NET 2.0 has enhanced a lot in order to make our application more scalable and much more flexible ,one of the major enhancement in ADO.NET 2.0 is highly integration with SQL Server 2005 (YUKON) .YUKON ships with CLR to host managed code here I am illustrating how to host ADO.NET code in SQLCLR .
Have a look at the ADO.NET 1.0 code snippet
using System;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class MySample
{
public void MyConn()
{
SqlConnection connObj = new SqlConnection(“server=TestServer; database=Emp; user id=anand; password=$nand”);
connObj.Open();
SqlCommand cmdObj = new SqlCommand(“SELECT Name, Sal FROM Emptbl”, connObj);
SqlDataReader redObj = cmdObj.ExecuteReader();
while (redObj.Read())
{
// do your stuff}
}
}
}
}
Now lets try to host this code in SQLCLR for this you need to create a database project ( File | New|Project… select Database as project type) and click on SQL Server Project .Once you create the project it will prompts for server detail , specify the server name, access mode( Windows Authentication or SQL Authentication) and select the database you want to connect .After the above step you need to create managed stored procedure to do this select Project|Add New Item… and chose Stored Procedure , click on Add button to add the file to project below is the actual code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void StoredProcedure2()
{
SqlConnection connObj = new SqlConnection(“server=TestServer; database=Emp; user id=anand; password=$nand”);
connObj.Open();
SqlCommand cmdObj = new SqlCommand(“SELECT Name, Sal FROM Emptbl”, connObj);
SqlDataReader redObj = cmdObj.ExecuteReader();
while (redObj.Read())
{
// do your stuff}
}
}
};
Note: Set the permission to EXTERNAL_ACCESS (right-click on the project node,select Properties|Database tab, and then from the Permission Level combo-box, select External)
Now the next BIG thing is how to run this in SQL Server 2005. Visual Studio makes it trivial to deploy the assembly to SQL Server and take the appropriate steps to register each of the objects in the assembly with the server. After compile to code select Build | Deploy Solution it will connect to SQL Server send the assembly to the server and register it and then register the stored procedure that you added to the assembly.The final step it to press F5 and start execute the code even you can debug the T-SQL and managed code .