我有一个存储过程,它返回一个结果集(一个select语句)和一个输出参数说@IsError
。仅当@IsError
设置为1时,才返回ResultSet。
现在我从另一个过程调用此过程,并且只有在@IsError
为1时才想从此过程中插入数据返回。
INSERT INTO #Order_Error(col1, col2, col3)
EXEC myStoredProc @param1, @param2, @IsError output
我想检查数据是否只应插入#Order_Error
,如果输出参数,@IsError
为1。
这里的参考是myStoredProc
定义。
CREATE PROC myStoreProc
( @param1 int,
@param2 varchar(50),
@IsError bit output
)
AS
BEGIN
BEGIN TRY
-- My T-SQL operations like insert or update to the table. Nothing returns from this block i.e. No SELECT statement.
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage
SET @IsError = 1
END CATCH
END
我不知道该怎么做。任何帮助将是欣赏。感谢
答案 0 :(得分:2)
你无法做到这一点。但是你可以使用staging表,如:
CREATE PROCEDURE spTest
@IsError BIT OUTPUT
AS
SET @IsError = 1
SELECT 1 AS A, 2 AS B
GO
DECLARE @IsError BIT
CREATE TABLE #Final(A INT, B INT)
CREATE TABLE #Staging(A INT, B INT)
INSERT INTO #Staging
EXEC spTest @IsError OUTPUT
IF @IsError = 1
BEGIN
INSERT INTO #Final
SELECT * FROM #Staging
END
SELECT * FROM #Final
DROP TABLE #Final
DROP TABLE #Staging
GO
ALTER PROCEDURE spTest
@IsError BIT OUTPUT
AS
SET @IsError = 0
SELECT 1 AS A, 2 AS B
GO
DECLARE @IsError BIT
CREATE TABLE #Final(A INT, B INT)
CREATE TABLE #Staging(A INT, B INT)
INSERT INTO #Staging
EXEC spTest @IsError OUTPUT
IF @IsError = 1
BEGIN
INSERT INTO #Final
SELECT * FROM #Staging
END
SELECT * FROM #Final
DROP TABLE #Final
DROP TABLE #Staging
GO
输出1:
A B
1 2
输出2:
A B
另一种方法是在第二个存储过程中使用临时表,因为它将看到从外部创建的临时表:
如果在一个存储过程中创建临时表,例如, 称之为Proc1-所有其他存储的临时表都是可见的 从Proc1调用的程序。但是,那个临时表不是 任何调用Proc1的程序都可以看到。
CREATE PROCEDURE spTest
@IsError BIT OUTPUT
AS
SET @IsError = 1
INSERT INTO #Final
SELECT 1 AS A, 2 AS B
GO
DECLARE @IsError BIT
CREATE TABLE #Final(A INT, B INT)
EXEC spTest @IsError OUTPUT
SELECT * FROM #Final
答案 1 :(得分:2)
更新存储过程中的CATCH语句以包含INSERT语句:
CREATE PROC myStoreProc
( @param1 int,
@param2 varchar(50),
@IsError bit output
)
AS
BEGIN
BEGIN TRY
-- My T-SQL operations like insert or update to the table. Nothing returns from this block i.e. No SELECT statement.
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage
SET @IsError = 1
IF (@IsError = 1)
BEGIN
<INSERT statement for #Order_Error>
END
END CATCH
END