SQL Server 儲存過程返回結果集的幾種方式

2022-02-15 09:34:24 字數 3673 閱讀 5321

2023年12月18日 21:52:24 xxc1605629895 閱讀數 7033更多

分類專欄: sqlserver

最近用到了sql server的幾種結果集返回方法,這裡整理如下(注:使用sql server 的  adventureworks2008 示例資料庫)

-- 1. table function

use adventureworks2008

go

if exists (

select 1

from sys.objects

where [type] in (n'tf' ,n'if' ,n'fn')

and name = 'fn_getperson'

)

drop function dbo.fn_getperson

go

create function dbo.fn_getperson

(

@entityid int

)

returns @result table (entityid int ,persontype varchar(10) ,firstname varchar(50) ,lastname varchar(50))

as

begin

insert into @result

(

entityid

,persontype

,firstname

,lastname

)

select businessentityid

,persontype

,firstname

,lastname

from person.person

where businessentityid = @entityid

return -- return must be last sql

end

go

print('dbo.fn_getperson has been created.')

-- select * from dbo.fn_getperson(1)

-- 3. inline function

use adventureworks2008

go

if exists (

select 1

from sys.objects

where [type] in (n'tf' ,n'if' ,n'fn')

and name = 'fn_getperson2'

)

drop function dbo.fn_getperson2

go

create function dbo.fn_getperson2

(

@entityid int

)

returns table

as

return

select businessentityid

,persontype

,firstname

,lastname

from person.person

where businessentityid = @entityid

go

print('dbo.fn_getperson2 has been created.')

-- select * from dbo.fn_getperson2(1)

-- 3. procedure

use adventureworks2008

go

if exists (

select 1

from sys.procedures

where name = 'usp_getperson'

)

drop procedure dbo.usp_getperson

go

create procedure dbo.usp_getperson

(

@entityid int

)

as

begin

--....... do some process

-- result of last query will return

select businessentityid

,persontype

,firstname

,lastname

from person.person

where businessentityid = @entityid

end

go

print('dbo.usp_getperson has been created.')

-- exec dbo.usp_getperson @entityid = 1

注:sql server 只返回最後一條查詢的結果集

SqlServer如何獲取儲存過程的返回值

1.output引數返回值 1 create procedure dbo upinformation 2 age int,3 id bigint output4 5as6begin 7set nocount on 8begin 9insert into information age 10value...

sql server儲存過程

建立表的語句 create table student sno int primary key,sname nvarchar 30 sgentle nvarchar 2 sage int,sbirth smalldatetime,sdept nvarchar 30 drop table studen...

SQLSERVER儲存過程

sqlserver儲存過程使用說明書 引言首先介紹一下什麼是儲存過程 儲存過程就是將常用的或很複雜的工作,預先用 sql語句寫好並用乙個指定的名稱儲存起來,並且這樣的語句是放在資料庫中的,還可以根據條件執行不同 sql語句,那麼以後要叫資料庫提供與已定義好的儲存過程的功能相同的服務時,只需呼叫 ex...