I am writing a stored procedure and I want to return 0 records when something fails. I can't figure out how to simply return 0 rows? I used SELECT NULL , but this returns 1 row with NULL in row 1 col 1. I also tried not to specify any SELECT in my error code path, but when testing the @@ROWCOUNT after calling SP, it returned 1. I I think it could be because @@ROWCOUNT has never been reset from a SELECT earlier in SP (in EXISTS() ). Any advice would be appreciated.
In addition, I have XACT_ABORT , but I also used the TRY/CATCH block to ensure that the return value of the error is returned from the stored procedure. This is normal? If an error occurs, will XACT_ABORT override TRY/CATCH or will my error code path still return return values?
-- Setup SET NOCOUNT ON; -- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements. SET XACT_ABORT ON; -- SET XACT_ABORT ON rollback transactions on errors DECLARE @return int; SET @return = 1; -- Default to general error -- Start transaction BEGIN TRANSACTION BEGIN TRY IF NOT EXISTS(SELECT NULL FROM [MyTable] WHERE [Check] = 1) BEGIN -- Insert new record INSERT INTO [MyTable] (Check, Date) VALUES (1, GETDATE()); SELECT SCOPE_IDENTITY() AS [MyValue]; -- Return 1 row SET @return = 0; -- Success END ELSE BEGIN -- Fail SELECT NULL AS [MyValue]; -- Want to return 0 rows not 1 row with NULL SET @return = 2; -- Fail error END END TRY BEGIN CATCH -- Error ROLLBACK TRANSACTION; SELECT NULL AS [MyValue]; -- Want to return 0 rows not 1 row with NULL SET @return = 1; -- General error END CATCH -- End transaction and return COMMIT TRANSACTION RETURN @return;
sql sql-server tsql stored-procedures sql-server-2005
Michael waterfall
source share