저장 프로 시저의 출력을 SQL Server의 변수로 반환하는 방법
SQL Server에서 저장 프로 시저를 실행하고 출력을 변수에 할당하고 싶습니다 (단일 값을 반환 함)?
반환하려는 정보의 성격에 따라 다릅니다.
단일 정수 값이면 다음 return
문을 사용할 수 있습니다 .
create proc myproc
as
begin
return 1
end
go
declare @i int
exec @i = myproc
정수가 아닌 값 또는 스칼라 값이 많은 경우 출력 매개 변수를 사용할 수 있습니다.
create proc myproc
@a int output,
@b varchar(50) output
as
begin
select @a = 1, @b='hello'
end
go
declare @i int, @j varchar(50)
exec myproc @i output, @j output
데이터 세트를 반환하려면 다음을 사용할 수 있습니다. insert exec
create proc myproc
as
begin
select name from sysobjects
end
go
declare @t table (name varchar(100))
insert @t (name)
exec myproc
커서를 반환 할 수도 있지만 그저 끔찍하므로 예제를 제공하지 않습니다. :)
return
저장 프로 시저 내 에서 문을 사용하여 정수 상태 코드 (및 정수 유형 만)를 반환 할 수 있습니다 . 일반적으로 성공을 위해 반환 값 0이 사용됩니다.
no return
가 명시 적으로 설정된 경우 저장 프로시 저는 0을 반환합니다.
CREATE PROCEDURE GetImmediateManager
@employeeID INT,
@managerID INT OUTPUT
AS
BEGIN
SELECT @managerID = ManagerID
FROM HumanResources.Employee
WHERE EmployeeID = @employeeID
if @@rowcount = 0 -- manager not found?
return 1;
END
And you call it this way:
DECLARE @return_status int;
DECLARE @managerID int;
EXEC @return_status = GetImmediateManager 2, @managerID output;
if @return_status = 1
print N'Immediate manager not found!';
else
print N'ManagerID is ' + @managerID;
go
You should use the return value for status codes only. To return data, you should use output parameters.
If you want to return a dataset, then use an output parameter of type cursor
.
Use this code, Working properly
CREATE PROCEDURE [dbo].[sp_delete_item]
@ItemId int = 0
@status bit OUT
AS
Begin
DECLARE @cnt int;
DECLARE @status int =0;
SET NOCOUNT OFF
SELECT @cnt =COUNT(Id) from ItemTransaction where ItemId = @ItemId
if(@cnt = 1)
Begin
return @status;
End
else
Begin
SET @status =1;
return @status;
End
END
Execute SP
DECLARE @statuss bit;
EXECUTE [dbo].[sp_delete_item] 6, @statuss output;
PRINT @statuss;
With the Return statement from the proc, I needed to assign the temp variable and pass it to another stored procedure. The value was getting assigned fine but when passing it as a parameter, it lost the value. I had to create a temp table and set the variable from the table (SQL 2008)
From this:
declare @anID int
exec @anID = dbo.StoredProc_Fetch @ID, @anotherID, @finalID
exec dbo.ADifferentStoredProc @anID (no value here)
To this:
declare @t table(id int)
declare @anID int
insert into @t exec dbo.StoredProc_Fetch @ID, @anotherID, @finalID
set @anID= (select Top 1 * from @t)
ReferenceURL : https://stackoverflow.com/questions/11965269/how-to-return-the-output-of-stored-procedure-into-a-variable-in-sql-server
'developer tip' 카테고리의 다른 글
Python에서 산 세척 이해하기 (0) | 2021.01.06 |
---|---|
Android SharedPreferences 모범 사례 (0) | 2021.01.06 |
코드 서명 ID 란 무엇입니까? (0) | 2021.01.06 |
C #에서 모든 컨트롤러 및 작업 이름 가져 오기 (0) | 2021.01.05 |
Python : ( "hello"는 "hello")가 True로 평가되는 이유는 무엇입니까? (0) | 2021.01.05 |