Thursday, August 14, 2008

CLR SP in C#

We always use sql in .net but have you ever used .net in sql.
Now we shall write strored procedure in .net and make an assembly of it.

First create a table
USE TESTG2
CREATE TABLE NAMETABLE (
ID INT NOT NULL PRIMARY KEY IDENTITY(1,1),
NAME VARCHAR(50) NOT NULL,
TITLE VARCHAR(20))

1. Open Visual studio
2. Create Project
3. Select Database from left pane of New Project window
4. Select SQL Server Project
5. Name it csNAMETABLE
6. On Add Database Reference window Click on TestG2.dbo reference or if not there click on "Add Refence" and choose it.
7. Add New Item > Choose "Stored Procedure" and name it Insertion.cs > Add
8. Now you have a partial class "StoredProcedures" and a static method called "Insertion()"
9. Now you need two parameters : Name and Title, so provide these parameters to the method like
public static void Insertion(string Name, string Title) { }

10. Now first you need to create a connection
SqlConnection conn = new SqlConnection ();

11. As this connection will take the context where it will be running (under which database) so put it like
conn.ConnectionString = "Context Connection=true";

12. Take an instance of SqlCommand
SqlCommand cmd = new SqlCommand ();

13. Attatch connection to the command
cmd.Connection = conn;

14. Open the connection
conn.Open ();

15. Give the commandText
cmd.CommandText = @"INSERT INTO NameTable(Name, Title) values('" + name + "','" + title + "')";

16. Run the ExecuteNonQuery()
cmd.ExecuteNonQuery ();

17. Close the connection.
conn.Close ();

18. And we are done.

19. Now Build and deploy.

**Now first you need to change the configuration of database as clr enabled.

sp_configure 'clr enabled', 1
go

**Once clr is enabled, Reconfigure it
reconfigure
go
/****************************************************/
Now go to Query Analyzer and run
exec INSERTION 'My Name', 'Mr.'
go


NOTE: As C# is restricted with Default value in parameter, you can not set default value for its parameter. So you need to define another procedure which can take parameters to like
CREATE PROCEDURE InsertAll
@Name [nvarchar](4000),
@Title [nvarchar](4000) = 'Mr.'
AS EXTERNAL NAME [CSNAMETABLE].[StoredProcedures].[Insertion]


Now your this InsertAll procedure shall serve the purpose if you want to give either Name only or Name and Title both.

Keep going - keep digging.

Happy SQLing

No comments: