【SqlServer】SqlServer程式設計語言T-SQL的預存程序

來源:互聯網
上載者:User

標籤:實現   www.   傳遞參數   name   建立   shu   方法   product   tar   

我們一開始學習資料庫語言的時候就是用一些簡單的insert,select等文法,但是隨著我們學習資料庫的深入,就會發現一些簡單的文法滿足不了我們的要求,比如處理一些商務邏輯,多表關聯的時候,還有就是雖然程式或是簡單的sql語句也會實現其效果,但是效能或是效率會很低。

  這時候我們就會用到T-sql中的預存程序,預存程序就像C#中的方法一樣,傳遞參數,執行一些操作,返回相應的值。

  我們用SQLSERVER2008內建的AdventureWorks樣本資料庫來講解。

  首先我們建立一個預存程序,關鍵字為Procedure,範例程式碼: 

 

create procedure proc_Sales_SalesReasonasbegin    select * from Sales.SalesReason;end

 

  我們建立的一個proc_Sales_SalesReason預存程序,執行查詢操作,一般預存程序命名為proc_+名稱,這樣有利於識別。

 

  執行預存程序範例程式碼:

 

execute proc_Sales_SalesReasondrop procedure  proc_Sales_SalesReason    --刪除預存程序

 

  修改預存程序的話用alter關鍵字。

 

  以上只是簡單的預存程序,就想無參數的方法一樣,下面是帶參數的範例程式碼:

 

create procedure proc_Sales_SalesReason(@SalesReasonID int, @Name nvarchar(50), @ReasonType nvarchar(50), @ModifiedDate datetime)asbegin insert into Sales.SalesReason(SalesReasonID, Name, ReasonType, ModifiedDate) values(@SalesReasonID, @Name, @ReasonType, @ModifiedDate);end

 

  這是一個執行插入資料的預存程序,執行範例程式碼:

 

execute proc_Sales_SalesReason 100,‘text1‘,‘as‘,‘2011-12-12‘;

 

  以上講解的都是一些簡單預存程序的用法,在這裡只是起到拋磚引玉的作用,大家可以有時間好好研究下,去處理一些複雜的商務邏輯。

 

  下面我做了一個小樣本

 

  select :按價格範圍來查詢
  要求:如果兩個參數均存在,則表示查詢該指定範圍的內容;
  若均不存在,則查詢所有
  若@PriceFrom參數存在,則,查詢>[email protected]
  @priceTo存在,則<[email protected]

 

create procedure proc_SelectProductsWithPriceRange(    @PriceFrom money, @priceTo money)as begin if @PriceFrom is not null begin if @priceTo is not null begin select *from dbo.Products where Price between @PriceFrom and @priceTo; end else begin select *from dbo.Products where Price>=@PriceFrom; end end; else begin if @priceTo is not null begin select *from dbo.Products where Price<=@priceTo; end else begin select *from dbo.Products end end end;

 

  執行預存程序:

 

execute proc_SelectProductsWithPriceRange 17,null

  

原文連結:T-sql 預存程序

【SqlServer】SqlServer程式設計語言T-SQL的預存程序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.