CLR User Defined Functions Part I

by Volem October 25, 2010 10:12

Microsoft teknolojilerinin ne kadar icli disli oldugunu biliyorsunuzdur. Ornegin siz bir web uygulamasinin icinde Excel sheet, windows uygulamasinin icinde explorer nesnesini cok da ugrasmadan kullanabilirsiniz. Bu iliskiye benzer bir iliski ile C# veya VB.NET de yazdiginiz bir metodu bir MS SQL Server fonksiyonuna nasil cevirebilirsiniz sorusunu yanitlamaya calisacagim. Bu 3 alt makaleden olusan yazi dizisinin 1.si..

Microsoft SQL 2005 Server'dan itibaren CLR(Common Language Runtime) User defined functions (kullanici tanimli fonksiyonlar) tanimlamamiza izin veriyor. Bu yazimda oncelikli olarak size scalar bir deger donduren bir fonksiyonu sql server'a nasil tanitacagimizi anlatmaya calisacagim.

Oncelikle C# kodumuza bir goz atalim..

using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

namespace ArticleCodes
{
    public class CLRScalarValuedFunction
    {
        [SqlFunction(DataAccess=DataAccessKind.Read)]
        public static int GetCompanyCount()
        {
            using (SqlConnection conn = new SqlConnection("context connection=true"))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("SELECT COUNT(*) AS companyCount FROM Companies", conn);
                return (int)cmd.ExecuteScalar();
            }
        }
    }
}

Bir scalar fonksiyon tanimlamak icin oncelikle metodumuzun static bir metod olmasi gerekiyor. Yukaridaki kod kendini anlatiyor diye dusunuyorum. Burada dikkatinizi cekmek istedigim kisim SqlConnection tanimi.. Dikkat ederseniz alisila gelmis connection string'lerden biraz farkli.

SqlConnection conn = new SqlConnection("context connection=true")

Peki neden boyle bir tanim yaptik ve bu tanim bize ne anlatiyor. Oncelikli olarak biz bu metodu SQL Server'a tanitacagiz ve bu bir veritabanina ya da master'a tanimli olacaktir. Dolayisiyla metodu kullanacak olan kisi zaten bir veritabani baglantisi yapacak ve ardindan bizim metodumuzu kullanacaktir. Biz iste bu baglantidaki yetkileri ile bu metodu cagiriyoruz. Dolayisiyla guvenli bir baglanti yapiyoruz. Eger bu metodu cagirma ya da bu veritabanina baglanma ve yahut da veri cekme yetkisi yok ise bu kontrolleri yapmamiza gerek kalmiyor. Context Connection ile ilgili detayli bilgi icin buraya bi goz atabilirsiniz.

Bunun disinda dikkat etmemiz gereken husus metodumuzun giris parametreleri ve donus degeridir. Bunlarin SQL Server tarafindan desteklenen scalar deger tipleri olmasi gerekiyor. Bu konuda da suraya bi bakin derim.

Simdi gelelim bu yazdigimiz ve derledigimiz metodu nasil SQL Server'a tanitacagimiza..

CREATE ASSEMBLY CLRCodes FROM '<DLL'in tam yolu(full path)>'

Bu T-SQL komutunu metodumuzu tanimlamak istedigimiz veritabanimizda calistiriyoruz. Boylece tanimladigimiz dll artik SQL server tarafindan benimsenmis oluyor. Ardindan yapilacak ikinci iş, metodumuzu tanimlamak..

CREATE FUNCTION GetCompanyCount() RETURNS INT
AS EXTERNAL NAME <assembly adi>.[<namespace>.<class adi>].<method adi>

Yani verdigim ornege gore

CREATE FUNCTION GetCompanyCount() RETURNS INT
AS EXTERNAL NAME CLRCodes.[ArticleCodes.CLRScalarValuedFunction].GetCompanyCount

Bu komutlari calistirdiktan sonra goreceksiniz ki assembly altinda CLRCodes adinda bir dll ve Scalar-Valued functions altinda GetCompanyCount adinda bir metod olusturulmustur. Metodu test etmek icin

SELECT [dbo].[GetCompanyCount]()

querisini calistirabilirsiniz.

Ancak kodu test ettiginizde muhtemelen "CLR not enabled" benzeri bir hata alacaksiniz. Buradan da sunu cikariyoruz; SQL Server default olarak sizin .NET kodunuzu desteklemiyor. Bunu desteklemek icin ise asagidaki kodu calistirabilirsiniz.

EXEC sp_configure 'clr enabled' , '1'
go
reconfigure;
go

Umarim isinize yarar...

Tags: , ,

C# | SQL

Comments

4/6/2012 11:51:36 PM #

@RichardKovitch yeah Slits > Rip, Rig & Panic > Raw Like Sushi (also Sherwood adamnat that Blue Lines is basically a Singers & Players LP)

Chantal Soders United States

4/10/2012 1:13:20 PM #

I love your Oompa minutes! This video helped me to find a place to easily purchase my young child's school supplies. I watch your new minutes every time I log onto your website. In a world where every thing is made in China your website makes it easy for me to purchase safe and healthy toys for my children. Your website is also my go-to spot for all children birthday parties! I love your products, keep up the good work!

Vanetta Ganibe United States

4/10/2012 1:18:11 PM #

Of course, what a great site and informative posts, I will add backlink  bookmark this site? Regards, Reader

led zarulje United States

4/11/2012 1:25:14 AM #

Would you believe that I listen to you everyday!!?? you provide an excellent break from my studies as my exams are soon and after I've finished, Im gunna rock all the hymns you've taught me with my youth at church. whoooooooooooop. Thank you, Coffey!

Terese Stjean United States

4/11/2012 6:11:44 PM #

I just wanted to say thank you to everyone at Carnoustie for looking after my Son and I when we visited your marvellous courses last month.For such a prestigious course, everyone we met were the friendliest and most welcoming people you could imagine, staff and members alike. I am recommending you all to our golfing acquaintances and really hope that one day we will have the opportunity to revisit.

Marnie Lanfor United States

4/11/2012 6:13:31 PM #

Scott: Thank you for your feedback. On a per LED basis, the amount of energy used in production is very small. Under normal usage, you recover the amount of energy used in LED production in less than a week.

led rasvjeta United States

4/12/2012 2:40:38 PM #

I cant here other side voice.but other side can here my sound.how can i sortout this problem

Olympia Stemarie United States

4/12/2012 10:33:08 PM #

How did your appointment go with Interface Talent Network, Lorraine? I have read a couple of reviews online about this talent agency and they seem like the real deal.

Andera Sissom United States

4/13/2012 5:45:56 PM #

My English is not so good. Please excuse that.

Deandre Vanderhoef United States

4/14/2012 10:23:36 AM #

Magical Urbanism, Alexander von Hoffman, Robert O. Keel, Tim O'Neil e The Economist (blog Prospero).

Denny Merced United States

4/18/2012 6:40:56 AM #

Eagles are beautifully amazing creatures, but, just remember, they will prey on a small dog or cat. in your back yard; so aware and protect your animals. They've made a big come back in my area, I've heard of several familys that lost their pets to eagles.

บ้านมือสอง United States

4/18/2012 6:44:36 AM #

Hi i just came across your site from Google but encountered a wierd popup about dog hospitals which is obviously unrelated to your site. Is this your advertising or do i have a spyware issue? Thanks.

บ้านเดี่ยว United States

4/25/2012 1:48:47 AM #

They're skipping his turn in the rotation and making him available in the rotation until his spot comes up again. I don't think it's a permanent move.

Marlon Hagglund United States

5/5/2012 8:14:57 PM #

Like my very own nanna pointed out one day, you may be best served just by all by yourself. Truly, I'm not sure the reason I'm informing you of that I simply want you to definitely be aware that this post is a great choice. Adios for now

debrider United States

5/6/2012 2:26:52 PM #

Nice Web Site and so much information for New bie php Developer like me thanks for sharing us keep sharing

Haley Serfling United States

Add comment




  Country flag
Click to change captcha
biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen | Modified by Volem

RSS
View Volkan Nazmi Metin's profile on LinkedIn

RevolverMap

Son Eklenen Yazılar

Yazar Hakkında

Sosyal, evli, çocuklu, karısını ve kızını çok seven, gezmeyi seven, spor yapmak isteyen bir mühendis