寫sql存儲過程經常需要調用一些函數來使處理過程更加合理,也可以使函數復用性更強,不過在寫sql函數的時候可能會發現,有些函數是在表值函數下寫的有些是在標量值下寫的,區別是表值函數只能返回一個表,標量值函數可以返回基類型。
舉個例子,當用戶刪除一個節點的時候,是需要將當前節點下的所有子節點都刪掉,如果程序只傳一個當前節點,那就需要寫一個函數來得到當前節點下的所有子節點,這些子節點的信息就可以放到一個表中返回。
ALTER FUNCTION testGetSubNodes
(
-- Add the parameters for the function here
@nodeId int
)
RETURNS
@t TABLE
(
-- Add the column definitions for the TABLE variable here
id bigint identity(1,1) not null,
nodeIds int ,
nodeName varchar(500)
)
AS
BEGIN
-- Fill the table variable with the rows for your result set
insert into @t values(@nodeId,'header');
while exists(
select nodeid from dbo.Tree where parentid
in (select nodeIds from @t) and nodeid not in(select nodeIds from @t))
begin
insert into @t select nodeid, nodename from dbo.Tree where parentid
in (select nodeIds from @t)
end
RETURN
END
這個函數的主要功能就是返回當前節點下的所有子節點,在存儲過程中寫
select * from testGetSubNodes(nodeId)就可以返回表中的數據了。
再寫一個標量值函數
ALTER FUNCTION [dbo].[testGetSubNodes_]
(
@nodeId int
)
RETURNS int
AS
BEGIN
declare @nodeCount int
select @nodeCount=5 from MenuTree
return @nodeCount
END
這個函數很簡單返回一個整型值,然后就可以在存儲過程中調用了,不過調用的方式有所不同,象上面的表值函數調用是不需要所有者的,只要寫函數名稱就可以,對於標量值函數來說,是需要加上所有者的,比如所有者是dbo
select dbo.testGetSubNodes_,這樣就可以返回5,如果不加dbo,那sql會不認識這個函數。