Click here to Skip to main content
16,017,231 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi All,

I have to write a stored proc in which I need to update some table based on another table's result. Let us take an example with Receipt No. 26.

We have following requirements:

1). Update single column in tbla where Receipt No. 26.
2). Select multiple rows's columns(Invno,Adjamt) from tblb where Receipt No. 26.
3). Update tblc where c.Invno=b.Invno

What will be the best way to do so?

Regards!
Aman
Posted
Updated 17-Feb-11 0:05am
v2

Something like this...

SQL
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE  [dbo].[receipts_UpdateReceiptDetails]
	(
		@ReceiptID			INT,
		@SomeNewValue		INT
	)

AS

SET NOCOUNT ON

/*
__________________________________________________________________________________________
Author:			Dylan Morley
Description:		

Created:		
Modification History:	Date		Modified By	Modification
			[dd/mm/yy]	[Name]		[Desc]

__________________________________________________________________________________________
*/

BEGIN TRY
	BEGIN TRANSACTION

	UPDATE
		TBLA
	SET
		WhateverColumn = @SomeNewValue
	Where
		ReceiptNo = @ReceiptID
	
	UPDATE 
		TBLC
	SET
		WhateverColumn = B.Adjamt
	FROM
		TBLC
	JOIN
		(
			SELECT 
				Invno, Adjamt
			FROM	
				tblb 
			Where
				ReceiptNo = @ReceiptID		
		)
	AS 
		B
	ON
		TBLC.Invno = B.InvNo

	COMMIT
	
END TRY
BEGIN CATCH

  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

-- Return any error codes \ Reset the NOCOUNT property.
RETURN @@ERROR
SET NOCOUNT OFF
 
Share this answer
 
v2
Comments
Aman4.net 17-Feb-11 7:04am    
Thanx for your efforts! You really saved time.
thatraja 17-Feb-11 21:13pm    
Have a 5 for your effort
Hope this[^] and
this[^]might help you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900