Search This Blog

Showing posts with label Sql Server. Show all posts
Showing posts with label Sql Server. Show all posts

Friday, November 19, 2010

Try Catch block in a Transaction

We can use TRY catch blocks from SQL Server 2005 onwards and can rollback a transaction if there were any errors. Please see the example below


BEGIN TRY
 SET XACT_ABORT ON -- Will rollback on any errors
 BEGIN TRANSACTION    -- Start the transaction
   DELETE FROM Mytable
WHERE id = 'something'
   -- If we reach here, success!
   COMMIT
END TRY
BEGIN CATCH
  -- Whoops, there was an error
  IF @@TRANCOUNT > 0
     ROLLBACK

  -- Raise an error with the details of the exception
  DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
  SELECT @ErrMsg = ERROR_MESSAGE(),
         @ErrSeverity = ERROR_SEVERITY()

  RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH

Friday, November 12, 2010

Checking data in database before going for any inserts

We commonly encounter a scenario where we have to check if a data is already there in table before going for any insertions. So here is a quick query for this purpose

please note that i wrote this query keeping Sql Server in mind.

IF NOT EXISTS ( SELECT TOP 1 [NAME] FROM myTable WHERE [Name] = 'check_name' )
BEGIN

INSERT INTO myTable
           ([Name]
           ,[Description]
           )
     VALUES
           ('check_name'
           ,'test'
           )
END

Tuesday, October 26, 2010

Searching for a text on SQL Server (PL SQL Style)

Hi those coming from a PL SQL background will be knowing of a very common functionality which enables you to search for a particular text through PL SQL Dev tool on a particular text. Now if you try to look for a same type of a feature on SQL Server Management Studio, there is none.


The work around is the following stored procedure.
SELECT OBJECT_NAME(id)
FROM syscomments
WHERE [text] LIKE '%foobar%'
AND OBJECTPROPERTY(id, 'IsProcedure') = 1
GROUP BY OBJECT_NAME(id)

So if you want to search for a text like foobar in all procedures used in the database, the query would look like something above. If the same thing has to be searched in a function then the parameter "IsProcedure" has to be changed to "IsFunction".


This tip will particularly important if you are associated with support and enhancement kind of activity and need to find say "How many times a particular table name is used in a procedure or a function".