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] — 刪除臨時表

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM