Tuesday, March 19, 2013

a better SQL example on output parameters, transactions, and selecting TOP 1

USE [Foo]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_IMS_GetNextAutoNumberAvailable]
   @NextAutoNbr int = 0 OUTPUT
AS
BEGIN TRANSACTION incrementSA
   DECLARE @NextIncrement int
   Select @NextIncrement = (SELECT TOP 1 SettingIntValue FROM Settings WHERE
         SettingName = 'SA')
   SET @NextIncrement = @NextIncrement + 1
   UPDATE Settings SET SettingIntValue = @NextIncrement WHERE SettingName = 'SA'
   SET @NextAutoNbr = @NextIncrement
COMMIT TRANSACTION incrementSA

No comments:

Post a Comment