Trapping errors while truncating a table

  • Hi,

    I need to write a stored procedure for a web application that simply truncates a table from the database after a certain activity. 

    I need help in trapping errors that go with Truncate Table statement.  @@ Error does not seem to work here. 

    What I am looking for is something like

    Truncate table TABLE

    IF there is an error

    PRint 'Error!'

     

    Thanks

    KR

  • Not all errors are trappable in SQL server, especially TRUNCATE TABLE is something that should be thought very well  due to the elevated priviledges required. For such control you will need Client side code.

     


    * Noel

  • Do a count(*), or some other potentially more efficient but predictable operation which returns a rowcount after the truncate.  If you have rows, the truncate failed and you can raise the error.


    And then again, I might be wrong ...
    David Webb

  • Thanks to both of you for you input

    KR

  • Hmmm how about something like:

    DECLARE @i INT

    SELECT TOP 1 @i = clustered_index_column FROM mytable

    IF @i IS NOT NULL

    BEGIN

        RAISERROR ...

    END

    Assumes your clustered_index_column is non-nullable of course.

  • IF EXISTS(SELECT 1 FROM mytable)

     RAISERROR (...)

    No need for variables or anything.

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass
  • hehe Excellente!

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply