儲存過程和使用者自定義函式

2021-09-05 20:13:27 字數 3443 閱讀 2336

一:儲存過程的簡單建立,修改與刪除

1.建立簡單的儲存過程

useadventureworks

gocreate

proc

spemployee

asselect

*from

humanresources.employee

執行上面的**就建立了乙個儲存過程

如果想執行這個儲存過程

可以直接執行exec spemployee這個語句

2.更改儲存過程

alter

proc

[dbo].

[spemployee]as

select

top13

*from

humanresources.employee

3.刪除儲存過程

drop

proc

dbo.spemployee

二:儲存過程的輸入引數和輸出引數

1.有輸入引數的儲存過程

useadventureworks

gocreate

proc

spemployee

@lastname

nvarchar(50

) =null

asif

@lastname

isnull

select

top13

*from

humanresources.employee

else

select

top10

*from

humanresources.employee

檢視該儲存過程的結果可以用

exec spemployee '123'

或直接exec spemployee

儲存過程的過載...

2.有輸出引數的儲存過程

useadventureworks

goalter

proc

spemployee

@lastname

nvarchar(50

) =null

output

asif

@lastname

isnull

begin

print

'null

'return

'123

'end

else

begin

print

@lastname

return

'456

'end

看第乙個測試該儲存過程的語句

declare

@myval

nvarchar(50

)exec

@myval

=spemployee 

@myval

output

print

@myval

輸出null  123

第二個測試該儲存過程的語句

declare

@myval

nvarchar(50

)set

@myval='

xland

'exec

@myval

=spemployee 

@myval

output

print

@myval

輸出xland  456

三:使用者定義函式

1.返回標量值的使用者定義函式

先做乙個簡單的日期處理函式

把長日期縮短成短日期

create

function

dbo.dayonly(

@date

datetime

)returns

varchar(12

)asbegin

return

convert

(varchar(12

),@date

,101

)end

為了測試上面的函式先做個指令碼

useaccounting

declare

@counter

intset

@counter=1

while

@counter

<=

10begin

insert

into

orders 

values(1

,dateadd

(mi,

@counter

,getdate

()),1)

set@counter

=@counter+1

end

然後檢索這個指令碼 新插入的資料記錄

useaccounting

select

*from

orders 

where

dbo.dayonly(date1) 

=dbo.dayonly(

getdate

())

2.返回表的使用者定義函式

先看例子

useadventureworks

gocreate

function

dbo.fncontactsearch(

@lastname

nvarchar(50

))returns

table

asreturn

(select

*from

person.contact 

where

lastname 

like

@lastname+'

%')

執行這個例子

useadventureworks

select

*from

fncontactsearch('ad

')3.綜合例子:返回表,有輸入引數

u***land

gocreate

function

dbo.fungetmytable

(@id

asint

)returns

@allrows

table

(id  

intnot

null

,title  

nvarchar

(max

) null)as

begin

insert

into

@allrows

select

id,title 

from

mytable 

where

id =

@idreturn

endgo

執行這個例子

select

*from

fungetmytable(1)

SQL使用者自定義儲存過程

無參儲存過程 go ifexists select from sysobjects where name 儲存過程名 drop procedure 儲存過程名 建立儲存過程 create procedure 儲存過程名 as 內容體有參儲存過程 在這裡插入 片 goif exists select ...

oracle儲存過程和自定義函式

學習中遇到的相關問題plsql是什麼?資料庫的物件 表 檢視 索引 序列 同義詞 儲存過程 儲存函式。儲存過程和儲存函式 指儲存在資料庫中供所有使用者程式呼叫的子程式叫儲存過程 儲存函式。相同點 完成特定功能的程式。區別 是否用return語句返回值。儲存函式可以通過return返回值,而儲存過程不...

儲存過程和自定義函式的區別

儲存過程和自定義函式的區別 difference between procedure and user defined function 首先來看一下儲存過程和自定義函式的概念 一 什麼是儲存過程?儲存過程可以使得對資料庫的管理 以及顯示關於資料庫及其使用者資訊的工作容易得多。儲存過程是 sql 語...