?
Solved

help with Update query -- t-sql

Posted on 2013-06-05
11
Medium Priority
?
242 Views
Last Modified: 2013-06-09
Hello Experts!

I am trying to capture an error message if the below transaction fails. In the CATCH block, I am setting the error message to @errormessage variable, but this will not work.

How can I capture that particular record for which the update failed?

declare @ErrorMessage varchar(4000) = ''

 BEGIN TRAN trn1
	BEGIN TRY
		update p
		set p.Professional_Id = s.Destination_Professional_Id
		from tblPhys p, dbo.Prof s
		where p.Professional_Id = s.Source_Professional_Id
		  and s.Source_Professional_Id IS NOT NULL
	      and EXISTS (SELECT * FROM dbo.tblPhys AS tp WHERE tp.Professional_Id = s.Destination_Professional_Id AND tp.PhysicianId = p.PhysicianId)
 COMMIT TRAN trn1
	END TRY
	BEGIN CATCH
		IF @@TRANCOUNT > 0 
		ROLLBACK TRAN trn1
		Set @ErrorMessage = @ErrorMessage +  ' Update Failed for ProfesstionalId from S: ' + convert(varchar(20), s.Destination_Professional_Id) + Error_message() + ' failed at trn1'
	END CATCH

Open in new window


Thanks in advance!!!!
0
Comment
Question by:ravichand-sql
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
  • +1
11 Comments
 
LVL 66

Expert Comment

by:Jim Horn
ID: 39223864
For starters, the alias s is only active in the statement it is used, and not in future statements, so in your CATCH block s.anything will have no meaning.

>How can I capture that particular record for which the update failed?
afaik the only way to pull this off would be to select the ID of the record, save it in a variable, then perform your UPDATE.
0
 

Author Comment

by:ravichand-sql
ID: 39223875
So, you mean I have to do 2 updates instead of 1. one for capturing the value and the other for performing the actual update ??
0
 
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 39223882
Inside the catch block use this

SELECT
    ERROR_NUMBER() AS ErrorNumber
    ,ERROR_SEVERITY() AS ErrorSeverity
    ,ERROR_STATE() AS ErrorState
    ,ERROR_PROCEDURE() AS ErrorProcedure
    ,ERROR_LINE() AS ErrorLine
    ,ERROR_MESSAGE() AS ErrorMessage;
0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 

Author Comment

by:ravichand-sql
ID: 39223894
Aneesh,

But this will not give me the record that made the update fail, right?
0
 
LVL 66

Expert Comment

by:Jim Horn
ID: 39223919
>So, you mean I have to do 2 updates instead of 1. one for capturing the value and the other for performing the actual update ??
One select to capture the PK, then your update.
That way the PK is in a variable if needed in the CATCH block to display in a custom error message.

Unless one of my peers here can demonstrate this is possible in 1 statement, afraid so.
0
 
LVL 66

Assisted Solution

by:Jim Horn
Jim Horn earned 750 total points
ID: 39223920
... or, throw your UPDATE into a cursor, then you have every value already as a parameter.
0
 

Author Comment

by:ravichand-sql
ID: 39223966
Jim,

I never worked on a cursor before, could you give me a sample for the update script I have attached above?
0
 
LVL 66

Expert Comment

by:Jim Horn
ID: 39223987
>could you give me a sample for the update script I have attached above?
See http://msdn.microsoft.com/en-us/library/ms180169.aspx

Warning:  Not easy to learn.
0
 
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 39224078
> But this will not give me the record that made the update fail, right?
thats correct, but you will get the error ...
0
 
LVL 75

Expert Comment

by:Anthony Perkins
ID: 39224187
I am trying to capture an error message if the below transaction fails
So why don't we start with what error are you are trying to capture caused by bad data? And please don't say any error.  Is is a Primary or Foreign Key or Check CONSTRAINT error?  What other errors are you trying to capture?
0
 
LVL 75

Accepted Solution

by:
Anthony Perkins earned 750 total points
ID: 39224210
What I am getting at is that you as the Developer know all the potential logical errors and should query for them explicitly.  We can certainly help you with that.

In the meantime, at the very least correct your code as follows:
DECLARE @ErrorMessage varchar(4000) = ''

BEGIN TRY
    UPDATE  p
    SET     p.Professional_Id = s.Destination_Professional_Id
    FROM    tblPhys p
            INNER JOIN dbo.Prof s ON p.Professional_Id = s.Source_Professional_Id
    WHERE   -- s.Source_Professional_Id IS NOT NULL  
            EXISTS ( SELECT 1
                     FROM   dbo.tblPhys AS tp
                     WHERE  tp.Professional_Id = s.Destination_Professional_Id
                            AND tp.PhysicianId = p.PhysicianId )
END TRY
BEGIN CATCH
    SET @ErrorMessage = @ErrorMessage + ' Update Failed for ProfesstionalId from S: ' + CONVERT(varchar(20), s.Destination_Professional_Id) + ERROR_MESSAGE() + ' failed at trn1'
END CATCH

Open in new window

Notes:

1.

The TRANSACTION is pointless

2.

Use ANSI JOINs

3.

The condition s.Source_Professional_Id IS NOT NULL is not necessary.  If it is NULL then it will be excluded because of the JOIN.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question