Sizinle paylaşacağım örneklerde “AdventureWorks” üzerinde çalışacağım. Veritabanı sunucusu olarak da SQL 2012’i kullanıyor olacağım.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 |
-- Store Procedure(saklı yordam)kavrami --Yaptığı iş: içerisindeki birden fazla sorgu alıp bu sorguları sirası ile çalıştırmaktadır. --Java tarafındaki metotlara benzetilebilir. --5 aşama --Keywords kontrolu(syntax kontrolu) --kolonların varlığı yokluğu --yazılan sorguya en hizli nasıl gidilir bilgisi --kodun derlenmesi --kodun calıştırılması --yazılan bir sorgu yukaradaki 5 aşamadan geçtikten sonra result set ekrana yansıtılır.Yukaradaki --steplerden biri basarısız olursa sql hata ile cevap verir. --Ancak bir sorgu procudore haline getirilir ise sadecei ilk çalıştılmada yukaradaki 5 step uygulanır --ilk çalıştırılmadan sonra Execution plan çıkartılır ve bu plan kaydedilir. --daha sonradaki çalıştırılmada Execution planm sayesinde 5 aşamada değilde son 2 aşamadan devam edilir --buda bize performans olarak doner --Sql injection denilen saldırı çeşitinden uygulamaları ve yazılım geliştiricileri kurtarmak --hazır kod bloğu olduğu için bir çok iş mantığı procudure içerisinde uygulanabilir. --Sql server da bir çok karmaşık işte procudurelerden faydanlamaktadır. --Otrneğin mail gonderme prosudure sp_send_dbmail --Yada bir tablo bir view yada bir procudure hakkında bilgi almak için gerekli olan sp_help procudure si --Bir view in içerisiğini okumak için gerekli olan sp_Depends procudure side sistem içerisinde gömülü olarak gelmektedir. --procuduler metotlar gibi olduğu için parametre alan almayan şekilde tanımlanabilir. --standart procudure yazalım. --create procedure ProcudureAdi --as --begin -- procudure içeriği --end --production.product tabloasunda ad ve renk kolonları getirecek olan procudure yazalım create procedure sp_UrunGetir--genelde sp ön eki ile isimlendirilir. as begin select Name,Color from Production.Product end --çalıştırılma execute sp_UrunGetir----1. çalıştırılma exec sp_UrunGetir--2. çalıştırma sp_urunGetir ---3 çalıştırma --procudureler geriye her değeri döndürmezler.Bir procudure yazıldığı ilk andan itibaren --geriye int değer çıkartmak için yazılmışlardır.İnt değer döndürülmek zorunda değildir. --Döndürülmediği durumlarda return ifadesi yazılmaz,ancak değer döndürmek istediğimizde return ifadesi --ile sadece int değer return edilebilir. --Farklı bir değer çıkartmak istiyorsak,OutPut tekniği uygulanır. --yazilan bir procudure veritabanın altında programmability sekmesinin altında görüntülenebilir. --Parametre alan procedure ---Dışarıdan aldığı id değerindeki ürünü ad fiyat ve color kolonlarını ekrana yazdıralım. create procedure sp_Urundetay ( @Id int--dışarıdan gelecek olan parametre tanımlanması ) as begin select Name,Color,listprice from Production.Product where ProductID=@Id -- Dışarıdan aldığımız parametre end exec sp_Urundetay @Id=1 -- bu şekilde gönderilebilir 1. exec sp_Urundetay 1 -- bu şekilde gönderilebilir 2. --iki parametre alan procedure --renk ve fiyat bilgisi alsın create procedure sp_UrunDetay2 ( @Renk nvarchar(10), @fiyat money ) as begin select Name,Color,listprice from Production.Product where Color=@Renk and ListPrice>@fiyat end exec sp_UrunDetay2 'Blue',50 exec sp_UrunDetay2 @fiyat=100,@Renk='Black'--karışık sira ile parametre göndermek --içerisinde ne gönderdiysek o gelen create procedure sp_HarfGetir ( @Harf nvarchar(10) ) as begin select *from Production.Product where Name like '%'+@Harf+'%' --yada like @karakter+'%' end exec sp_HarfGetir @Harf='cal' --geriye değer döndüren procedure --bizden renk alsın bu renkteki ürün sayısını döndürsün create proc sp_HowCount ( @Renk nvarchar(10) ) as begin declare @sayi int select @sayi=COUNT(*) from Production.Product where Color=@Renk return @sayi --geriye sadece int değer return edilebilir end declare @returnValue int exec @returnValue=sp_HowCount 'Black' print @returnValue ---Bir değişken tanımlayıp,procedure nin return ettiği değeri değişken üzerinde aldık --ornek: veri tabanına bir personel kaydedip bu personele verilen en son id değerini alalım create table Personel ( Id int identity(1,1),--otomatik art 1 den başla, birer birer art Ad nvarchar(20), Maas money ) --personeli kayıt yapılacak olan procedure yazalim --bizden 2 adet parametre alıcak ve geriye son identity değerini döndürecek alter proc sp_PersonelKaydet ( @Ad nvarchar(10), @Maas money ) as begin insert into Personel (Ad,Maas) values (@Ad,@Maas) ---en son id değerini alalım declare @lastId int select Top 1 @lastId=Id from Personel order by Id desc return @lastId end -- yada alter proc sp_PersonelKaydet ( @Ad nvarchar(10), @Maas money ) as begin insert into Personel (Ad,Maas) values (@Ad,@Maas) return @@IDENTITY--identity alanın en son değerini bir seferlik verir end --calistiralım declare @sonid int exec @sonid= sp_PersonelKaydet 'Ayse',300 print @sonid select * from Personel --Personel tablosunu ek olarak bilgiler tablosu ekleyelim create table PersonelBilgi ( Id int identity(1,1), PersonelId int, Adres nvarchar(Max), Telefon nvarchar(11) ) --Personel bilgi tablosunu insert eden bir procedure yazalim create proc sp_PersonelBilgiKaydet ( @personelId int, @Adres nvarchar(max), @Telefon nvarchar(11) ) as begin insert into PersonelBilgi (personelId,Adres,Telefon) values (@personelId,@Adres,@Telefon) end --şu anda elimizde 2 adet procedure var.birisi personel tablosuna biriside personelbilgi tablosuna --kayıt yapıyor,Ben bu iki procedure i kapsulleyen başka bir procedure yapıp tek seferde ikisininde ----birlikte çalıştıralım create proc sp_PersonelGenelKaydet ( @Ad nvarchar(max), @Maas Money, @Adres nvarchar(max), @Telefon nvarchar(11) ) as set Nocount off-- satır sayma kapatmak için off begin declare @lastId int exec @lastId=sp_PersonelKaydet @Ad,@Maas --birinci procedure çalıştı ve id değeri return edildi, --return edilen id değerini alıp,diğer procedure e parametre gönderiyoruz if (@lastId<>0) begin exec sp_PersonelBilgiKaydet @lastId,@Adres,@Telefon end return @lastId end declare @id int exec @id= sp_PersonelGenelKaydet 'Hakan',5000,'Mecidyekoy','55555654' print 'Personel'+ cast (@id as nvarchar(10)) + 'id degeri ile kaydedilmiştir' --procedure ornek --Productld değeri alıp,bu Id değerine sahip ürünün large photo değerini ekrana yazıcak olan procedure create proc sp_GetPicture ( @ProductId int ) as begin select ppf.largephoto from production.productphoto ppf join Production.productProductphoto pppf on pppf.ProductPhotoId=ppf.ProductPhotoID where pppf.productId=@ProductId end exec sp_GetPicture 1 select * from Production.ProductPhoto --Store Procedure Output kavramı: --Bilindiği gibi sql server da store procedurelerden geriye sadece int değer return edebiliyorduk --Farklı tipde herhangi bir değer return etmeye calıştığımızda hata ile karşılasırız.Peki biz --farklı tipde değeri bir procedure içerisinde nasıl çıkartacağız? ---Output parametre yöntemi ile bir procedureden birden fazla farklı tipde değer çıkartmak mümkündür ---Ornek : --Id değerini verdiğimiz bir ürünün adını output yöntemi ile çıkartalım create proc sp_GetName ( @ProductId int,--procedure dışından içeriye gelecek olan parametre @Ad nvarchar(Max)Output --procedure içerisinden dışarıya gidecek olan parametre ) as begin select @Ad=name from Production.Product where ProductID=@ProductId end --Procedureden dönecek olan out değeri alalım declare @ad nvarchar(max) exec sp_GetName 2,@ad Output print @ad --birden fazla değer output olarak çıkartmak --rengini verdiğimiz ürünün toplam ve ortlama fiyatlarını output olarak çıkartalım create proc sp_SumAVGByColor ( @Renk nvarchar(Max), @Ortalama money Output, @Toplam money Output ) as begin select @Toplam=SUM(ListPrice),@Ortalama=AVG(listprice) from Production.Product where Color=@Renk end --İki adet output değeri alalım declare @ort money,@top money,@color nvarchar(max) set @color='Red' exec sp_SumAVGByColor @Color,@ort Out,@top out print ' Rengi :'+ @color + ' olan ürünlerin değeri toplami : '+ cast(@top as nvarchar(10)) + ' Ortalama: ' + cast(@ort as nvarchar(10)) --tüm ürünlerin toplam ,ortalama ,max,min değerini output --count değerini ise return edecek olan procedure yazalım create proc sp_DetayGoster ( @ortalama money out, @toplam money out, @Max money out, @min money out ) as begin select @toplam=SUM(Listprice),@ortalama=AVG(Listprice),@Max=MAX (listprice),@min=MIN(listprice) from Production.Product return (select COUNT(*) from Production.Product) end --değerleri alalım declare @max money,@min money,@sum money,@av money,@co int exec @co=sp_DetayGoster @av out,@sum out,@max out,@min out print 'Toplam :'+ cast(@sum as nvarchar(10)) print 'Ortalama :'+ cast(@av as nvarchar(10)) print 'Maximum :'+ cast(@max as nvarchar(10)) print 'Minimum :'+ cast(@min as nvarchar(10)) print 'Sayi :'+ cast(@co as nvarchar(10)) ------------------------------------------------------------------------------------------------------- create proc ortalayici ( @sayi1 smallint, @sayi2 smallint, @sayi3 smallint, @ortalama decimal(18,2) output ) as set nocount on select @ortalama=(@sayi1+@sayi2+@sayi3) / CAST(3 as decimal) set nocount off go declare @sonuc Decimal (18,2) exec ortalayici 1,2,4, @sonuc out select @sonuc yada -- declare @sonuc smallint exec ortalayici @sayi1=1,@sayi2=12,@sayi3=14,@ortalama=@sonuc out select 'ortalama',@sonuc go --------------------------------------------------------------------------------------------------- create table Ogr ( Id int identity(1,1), Ad nvarchar(Max), ) insert into Ogr values ('a') insert into Ogr values ('b') insert into Ogr values ('c') select * from Ogr delete from Ogr where Id=3 truncate table Ogr ---------------------------------------------------------------------------------------------------- --1 create table Personel ( Id int identity(1,1), Ad nvarchar(Max), Soyad nvarchar(Max) ) --2 create table PersonelBilgi ( Id int identity(1,1), Personelid int, Anaadi nvarchar(max), Babaadi nvarchar(max) ) --3 create table PersonelAdres ( Id int identity(1,1), PersonelId int, Il nvarchar(Max), Ilce nvarchar(Max), Semt nvarchar(Max) ) --4 create table Personeliletisim ( Id int identity(1,1), PersonelId int, Tel int , Email nvarchar(max) ) --5 create table PersonelSifre ( Id int identity(1,1), PersonelId int , Sifre nvarchar , ValidationValue nvarchar(max) ---select newId()-uniqueId üretiyor--özel id üretiyor ) --6 create table Kayitdetay ( Id int identity(1,1), PersonelId int, KayitTarih datetime ) --1 create proc sp_addPersonel ( @Ad nvarchar(10), @Soyad nvarchar(Max) ) as begin insert into Personel (Ad,Soyad) values (@Ad,@Soyad) return @@Identity end --2 create proc sp_addPersonelBilgi ( @PersonelId int, @Anaadi nvarchar(10), @Babaadi nvarchar(10) ) as begin insert into PersonelBilgi(Personelid,AnaAdi,BabaAdi) values (@personelId,@Anaadi,@Babaadi) end -- 3 create proc sp_addPersonelAdres ( @PersonelId int, @Il nvarchar(Max), @Ilce nvarchar(Max), @Semt nvarchar(Max) ) as begin insert into PersonelAdres (personelId,Il,Ilce,Semt) values (@personelId,@Il,@Ilce,@Semt) end ---4 create proc sp_addPersoneliletisim ( @PersonelId int, @Tel nvarchar(11) , @Email nvarchar(50) ) as begin insert into PersonelIletisim(PersonelId,Tel,Email) values (@personelId,@Tel,@Email) end --5 create proc sp_addPersonelSifre ( @PersonelId int , @Password nvarchar(10), @UniqueValue nvarchar(max) ) as begin declare @val nvarchar(max) set @val=NEWID() declare @pass nvarchar(10) set @pass=SUBSTRING(cast(NEWID()as nvarchar(max)),1,6) set @UniqueValue=@val set @Password=@pass insert into PersonelSifre(PersonelId,Sifre,ValidationValue) values (@PersonelId,@Password,@val) end --6 create proc sp_addKayitdetay ( @PersonelId int ) as begin insert into KayitDetay(PersonelId,KayitTarih) values (@PersonelId,Getdate()) end create proc sp_AddPersonelKayit ( @Ad nvarchar(10), @Soyad nvarchar(10), @Anaadi nvarchar(10), @Babadi nvarchar(10), @Il nvarchar(10), @Ilce nvarchar(10), @Semt nvarchar(10), @Tel nvarchar (20), @Email nvarchar(50) ) as begin if exists (select Email from PersonelIletisim where Email=@Email) begin print 'Lutfen farkli bir email adresi giriniz' end else begin declare @id int exec @id=sp_addPersonel @ad,@soyad end if(@id<>0) begin exec sp_addPersonelBilgi @id,@Anaadi,@babadi exec sp_addPersonelAdres @id,@Il,@Ilce,@Semt exec sp_addPersoneliletisim @id,@Tel,@Email declare @pass nvarchar(10) declare @uniqueval nvarchar(max) exec sp_addPersonelSifre @id,@pass output,@uniqueval output exec sp_addKayitdetay @id declare @mailBody nvarchar(max) set @mailBody='<table> <tr><td> ETC etc.com Aktivasyon Email" i</td> </tr> <tr><td>Merhaba Sayin' +@Ad + 'sistemimize' + cast(getdate() as nvarchar(max))+ 'tarihinde uye oldunuz.sistemimize kayit oldunuz <br /> Sifreniz:'+ @pass + 'olarak belirlenmistir.Lutfen aşağıdaki aktivasyonun tamamlanmasını sağlayınız <br /> <a href=http://www.google.com.tr?Unique= '+@uniqueval+'>Aktivasyon icin buraya tiklayiniz </a></td></tr> <tr><td> bu mail otomatik olarak gonderilmistir.</td></tr> </table>' exec msdb.sp_send_dbmail @profile_name='newmail', @recipients=@Email, @subject='Aktivasyon Email"i', @body=@mailBody, @body_format='HTML' end else begin print 'ilk kayit yapilamadigindan islem durdurulmustur' end end exec sp_AddPersonelKayit 'hasan','Aybaba','Filiz','Kenan','Izmir','Alsancak','Kordon cad.','55555544', 'deneme@yahoo.com' |