views:

69

answers:

2
BEGIN TRY 

    BEGIN TRANSACTION
       -- DO SOMETHIING

    COMMIT TRAN

END TRY
BEGIN CATCH
   IF(@@TRANCOUNT > 0)
     ROLLBACK TRANSACTION

   RAISERROR(ERROR_MESSAGE(), ERROR_SEVERITY(), ERROR_STATE()) --ERROR: Incorrect syntax near 'ERROR_MESSAGE'.

END CATCH

What wrong in the raise error statement?

+3  A: 

Error is occurring because you directly using function in RaiseError so to avoid this try the below code Try this is working for me

BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;
Pranay Rana
But why can't we use RaisError directly...
The King
dont know but i have debug whole given code in that i found that if i put functions directly instead of the variable it gives syntax error
Pranay Rana
I know its written here. http://msdn.microsoft.com/en-us/library/ms177497.aspx#CodeSpippet2. But shouldn't `RAISERROR(ERROR_MESSAGE(), ERROR_SEVERITY(), ERROR_STATE())` directly work?
Ismail
+4  A: 

RAISERROR follows the same rules as any other stored procedure call. Parameters passed in must be a constant or a variable. You cannot pass a function directly as a parameter. See Executing Stored Procedures for documentation on this.

/* Demo Code - Functions accept functions as parameters
               while stored procedures do not              */

create function dbo.fnDayOfWeek 
    (@date datetime) 
    returns int
as
begin
    declare @x int
    set @x = DATEPART(day,@date)
    return (@x)
end
go

/* Both statements are successful */
select dbo.fnDayOfWeek('2010-08-06')
go
select dbo.fnDayOfWeek(GETDATE())
go

drop function dbo.fnDayOfWeek
go

create procedure DayOfWeek
    @date datetime
as
begin
    select DATEPART(day,@date)
end
go

/* First call succeeds, second fails */
exec DayOfWeek @date = '2010-08-06'
go
exec DayOfWeek @date = getdate()
go

drop procedure DayOfWeek
go
Joe Stefanelli
Oh! I thought RAISEERROR is a function and not stored procedure.
Ismail
Functions are not subject to the same restrictions. I've appended some demo code to my answer to illustrate the difference.
Joe Stefanelli