1. 程式人生 > 資料庫 >SQL SERVER 獲取儲存過程返回值的幾種方法

SQL SERVER 獲取儲存過程返回值的幾種方法

--(1)不帶任何引數的儲存過程(儲存過程語句中含有return)

--建立儲存過程
CREATE PROCEDURE testReturn
AS
return 145
GO
--執行儲存過程
DECLARE @RC int
exec @RC=testReturn
select @RC
--說明
--查詢結果為145
--(2)帶輸入引數的儲存過程(儲存過程語句中含有return)
--建立儲存過程
create procedure sp_add_table1
@in_name varchar(100),
@in_addr varchar(100),
@in_tel varchar(100)
as
if(@in_name ='' or @in_name is null)
return 1
else
begin
insert into #table1(name,addr,tel) values(@in_name,@in_addr,@in_tel)
return 0
end
--執行儲存過程
--<1>執行下列,返回1
declare @count int exec @count = sp_add_table1 '','中三路','123456' select @count
--<2>執行下列,返回0
declare @count int exec @count = sp_add_table1 '','中三路','123456' select @count
--說明
--查詢結果不是0就是1
--(3)帶輸出引數的儲存過程(儲存過程中可以有return可以沒有return)

--例子A:
--建立儲存過程
create procedure sp_output
@output int output
as
set @output = 121
return 1
--執行儲存過程
--<1>執行下列,返回121
declare @out int
exec sp_output @out output
select @out
--<2>執行下列,返回1
declare @out int
declare @count int
exec @count = sp_output @out output
select @count
--說明
--有return,只要查詢輸出引數,則查詢結果為輸出引數在儲存過程中最後變成的值;只要不查詢輸出引數,則查詢結果為return返回的值

--例子B:
--建立儲存過程
create procedure sp_output
@output int output
as
set @output = 121
--執行儲存過程
--<1>執行下列,返回121
declare @out int
exec sp_output @out output
select @out
--<2>執行下列,返回0
declare @out int
declare @count int
exec @count = sp_output @out output
select @count
--說明
--沒有return,只要查詢輸出引數,則查詢結果為輸出引數在儲存過程中最後變成的值;只要不查詢輸出引數,則查詢結果為0
--3.Select資料集返回值
CREATE PROCEDURE [dbo].[upInformation](
@id int
)
AS
BEGIN
SET NOCOUNT ON;
SELECT id,age FROM [Information]
WHERE id = @id
GO

--儲存過程中獲得方法:(使用臨時表)
CREATE TABLE [dbo].[Temp](
[id] [bigint] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[age] [int] NOT NULL
)
INSERT [Temp] EXEC [nb_order_select] @id
– 這時 Temp 就是EXEC執行SELECT 後的結果集
SELECT * FROM [Temp]
DROP [Temp] — 刪除臨時表