Posts

Showing posts from March, 2011

SQL Stored procedure with error handling using Try/Catch

This is improved version of the script from 2009 using try/catch syntaxUSE [MyDatabase] GOPRINT 'DROP PROCEDURE [usp_mysproc]' GOifexists (select * from dbo.sysobjects where id = object_id(N'[dbo].[usp_mysproc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) dropprocedure [dbo].[usp_mysproc] GOPRINT 'CREATE PROCEDURE [usp_mysproc]' GOCREATEPROCEDURE [dbo].[usp_mysproc] ( @RaiseError bit = 0 ) ASBEGIN TRY BEGINTRANIF @RaiseError = 1 BEGINDECLARE @TEMPTABLE (Column1 varchar(2))

Select latest data from table

DECLARE @TEMPTABLE( Ticker varchar(50), Dateint, Details varchar(50) ) INSERTINTO @tempSELECT 'A',20110101,'A-1' UNIONSELECT 'B',20110101,'B-1' UNIONSELECT 'A',20110102,'A-2' UNIONSELECT 'C',20110102,'C-2' --Select whole universeSELECT * FROM @temp a ORDERBY a.Ticker --Select latest data (can't include Details)SELECT a.Ticker,MAX(a.Date) DateFROM @temp a GROUPBY a.Ticker ORDER