【发布时间】:2014-11-28 00:28:25
【问题描述】:
我需要从 SQL Server 存储过程的 CATCH 子句中返回一个包含数据库错误的结果集,但我还是坚持了下来。我是否需要使用游标来返回结果集?如果需要,那么我的 .NET 应用程序中 OUTPUT 参数的类型声明是什么?我试过Object 和Variant 但没有用。
我还尝试了使用SELECT 语句返回的简单方法,它适用于一个存储过程,但不适用于另一个存储过程,因此在我的CATCH 子句中:
while (@I <= @count)
begin
BEGIN TRY
-- delete all previous rows inserted in @customerRow for previous counts @I
delete from @customerRow
-- this is inserting the current row that we want to save in database
insert into @customerRow
SELECT
[id],[firstname], [lastname], [street], [city],
[phone],[mobile],[fax], [email], [companyName],
[licence],[brn], [vat], [companyStreet], [companyCity], [status]
FROM
(SELECT
ROW_NUMBER() OVER (ORDER BY id ASC) AS rownumber,
[id], [firstname], [lastname], [street], [city],
[phone], [mobile], [fax], [email], [companyName],
[licence], [brn], [vat], [companyStreet], [companyCity], [status]
FROM
@registerDetails) AS foo
WHERE
rownumber = @I
-- this stored procedure handles the saving of the current customer row just defined above
-- if there is any error from that sproc, it will jump to CATCH block
--save the error message in the temp table and continue
--with the next customer row in the while loop.
exec dbo.sp_SaveCustomer @customerRow
END TRY
BEGIN CATCH
IF @@TranCount = 0
-- Transaction started in procedure.
-- Roll back complete transaction.
ROLLBACK TRANSACTION;
if XACT_STATE()= -1 rollback transaction
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT @ErrorMessage = ERROR_MESSAGE() + ' ' + (select firstname from @registerDetails where id=@I)
SELECT @ErrorSeverity = ERROR_SEVERITY();
SELECT @ErrorState = ERROR_STATE()
INSERT INTO #registrationResults (error,id)
SELECT @ErrorMessage, @I
END CATCH
set @I = @I +1
end
COMMIT TRANSACTION registerTran
select * from #registrationResults
当我在我的 vb.net 代码中调用一个存储过程时,上述内容适用于:
ta.Fill(registrationErrors, clientDetailsDT)
其中registrationErrors 和clientDetailsDT 是强类型数据表。
这个没有:
begin catch
IF @@TranCount > 0 or XACT_STATE()= -1 ROLLBACK TRANSACTION;
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
DECLARE @ErrorLine INT;
SELECT @ErrorMessage = ERROR_MESSAGE();
SELECT @ErrorSeverity = ERROR_SEVERITY();
SELECT @ErrorState = ERROR_STATE();
SELECT @ErrorLine = ERROR_Line();
****ERROR -- THIS SELECT WAS MESSING ALL UP as it was this select that was being returned to the .NET and not the select of the desired #temp table after, hence returning 0 resultset as this select was EMPTY. !!
select status_indicator from InsertInvoiceTriggerData where session_GUID = guid**
delete from InsertInvoiceTriggerData where session_GUID = @guid**
INSERT INTO #registrationResults (error,id)
SELECT @ErrorMessage, NULL
select * from #registrationResults
end catch
关于如何返回结果集有什么建议吗?
【问题讨论】:
标签: sql-server vb.net resultset cursors