--10.7 例程
--10.7.1 使用者定義函式
--使用者定義函式(udf,user-defined function)的目的是要封裝計算的邏輯處理,有可能需要基於輸入的引數,並返回結果。
--sql server支援兩種使用者定義函式:標量udf和錶值udf。標量udf只返回單個資料值,而表值udf則返回乙個表。
--udf不允許有任何***.這一規定明顯的含義是udf不能對資料庫中的任何架構或資料進行修改.
use tsqlfundamentals2008;
if object_id('dbo.fn_age') is not null drop function dbo.fn_age;
gocreate function dbo.fn_age
(@birthday as datetime,
@eventdate as datetime)
returns int
as begin
return
datediff(year,@birthday, @eventdate)-
case
when 100*month(@eventdate)+day(@birthday)<100*month(@birthday)+day(@birthday) then 1
else 0
end
end;
goselect empid, firstname, birthdate, dbo.fn_age(birthdate, current_timestamp) as age
from hr.employees;
--10.7.2 儲存過程
--儲存過程是封裝了t-sql**的伺服器端例程.儲存過程可以有輸入和輸出引數,可以返回多個查詢的結果集,也允
--許呼叫具有***的**.通過儲存過程不但可以對資料進行修改,也可以對資料庫架構進行修改.
--儲存過程好處:
--1. 儲存過程可以封裝邏輯處理.如果需要修改儲存過程的實現,則只要在資料庫的乙個地方進行修改,儲存過程的所有
--使用者就能夠使用修改過的版本.
--2. 通過儲存過程可以更好地控制安全性.可以授予使用者執行某個儲存過程的許可權,而不是授予用於直接執行底層操作的
--許可權.此外,儲存過程也有助於避免sql注入,尤其是從客戶端通過引數來替換特殊的sql的注入形式.
--3. 在儲存過程中可以整合所有的錯誤處理,當有錯誤發生時,默默地進行糾正錯誤的操作.
--4. 儲存過程可以提高執行效能.儲存過程在預設情況下是重用執行計畫的,而sql server對其他特殊計畫的重用有更多
--的限制.使用儲存過程的另乙個好處是可以減少網路通訊流量.
use tsqlfundamentals2008;
if object_id('sales.usp_getcustomerorders', 'p') is not null drop proc sales.usp_getcustomerorders;
gocreate proc sales.usp_getcustomerorders
(@custid as int,
@fromdate as datetime = '19000101',
@todate as datetime = '99991231',
@numrows as int output)
asset nocount on;
select orderid, custid, empid, orderdate
from sales.orders
where custid=@custid
and orderdate>=@fromdate
and orderdate<@todate;
set @numrows=@@rowcount;
go--命令 set nocount on用於禁止顯示dml語句影響了多少行的訊息。
declare @rc as int;
exec sales.usp_getcustomerorders @custid=1,@fromdate=n'20070101',@todate=n'20080101',@numrows=@rc output;
select @rc as numrows;
第10章 可程式設計物件 1
第10章 可程式設計物件 10.1 變數 變數用於臨時儲存資料值,以供在宣告它們的同一批處理語句中引用。declare i as int set i 10 set i i select i as i declare j as int 10 use tsqlfundamentals2008 decla...
第10章 可程式設計物件 3
10.3 游標 可以用游標來處理查詢返回的結果集中的各行,以指定的順序一次只處理一行.游標的缺陷 使用游標嚴重違背了關係模型,關係模型要求按照集合來考慮問題.游標逐行對記錄進行操作會帶來一定的開銷.使用游標需要為解決方案的物理操作編寫很多 換句話說,得寫很多 來描述如何處理資料.set nocoun...
第2章 可程式設計邏輯器件與Verilog HDL
fpga是可程式設計邏輯器件 pld 的一種,多種工藝,不同原理的pld如下 基於乘積項結構的pld器件 基於查詢表結構的pld器件 原理圖輸入 hdl文字 hdl硬體描述語言 將原理圖或者hdl轉化為邏輯電源組成的電路網表 布局佈線後產生如下重要檔案 晶元資源耗用情況報告 產生延時網表結構,以便於...