Begin Catch Block Executed When Try Completes Without Error

Dec 10, 2007



I was just debugging a stored procedure visual studio and I was surprised with what I was watching.

I'm running SQL 2005 and visual studio 2005. I have a set of nested try/catch blocks.

It fails on the first try and drops into the catch block just as it should. Within the catch block a dynamic sql statement is created. A try block begins and attempts to exec(@sql). It then drops to the catch block. However, I copy the statement into SQL Management Studio and it runs without error everytime.

Why is it dropping into the catch block? Logically it should just complete executing the statement continue without going into the catch block.

Do I have to reset the raiserror values between try blocks or something?



--Thanks--



View 1 Replies


ADVERTISEMENT

How To Stop Execution Of Stored Procedure If Error Occurs In Try/catch Block

Mar 3, 2008



Hello, I have stored procedure that when executed it will check to see if a given name is found in the database, if the name is found, I would like to have it continue on to do its work, however if the name is not found, I would like it to raise an error and then stop execution at that point, however, the way it is currently working is, if the name is not found, it catches the error, raises it and then continues on and tries to do its work, which then it bombs out because it can't. I wasn't sure if there was a way to stop the execution of the procedure in the catch statement. I don't think I want to raise the error level to 20-25 because I don't want to drop the connection to the database per say, I just want to halt execution.

Here is a simple example of what I have:




Code Snippet
begin try

if not exists (select * from sys.database_principals where [name] = 'flea')

raiserror('flea not found', 16, 1)
end try
begin catch

declare @ErrorMessage nvarchar(4000);
declare @ErrorSeverity int;
select

@ErrorMessage = error_message(),
@ErrorSeverity = error_severity();
raiserror(@ErrorMessage, @ErrorSeverity, 1);
end catch
go

begin

print 'hello world'
end






At this point, if the user name (flea) is not found, I don't want it ever to get to the point of 'Hello World', I would like the error raised and the procedure to exit at this point. Any advice would be appreciated on how to best handle my situation!

Thanks,
Flea

View 5 Replies View Related

IF Statement With BEGIN END Block

May 4, 2006

I'm working on a stored procedure which includes an IF statement at the end of the procedure which appends my sql call with two lines. But I'm getting an error that probably comes from the fact that I have a nested BEGIN END block in my overall procedure. Can anyone tell me if my assumption is correct and help polish of the syntax?

The error I'm getting is:

Msg 156, Level 15, State 1, Procedure payments_sp, Line 55

Incorrect syntax near the keyword 'AND'.

and the sql code looks like this:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[payments_sp]
-- Add the parameters for the stored procedure here
@payment_type varchar(15),
@mydate smalldatetime
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
DECLARE @myBool1 tinyint, @myBool12 tinyint
SET @myBool1 = 1
IF (@payment_type = 'CODE1' OR @payment_type = 'CODE4')
SET @myBool1 = 1
ELSE
-- the payment type must be 'CODE1' or 'CODE2'
-- set the value to false
SET @myBool1 = 0
IF (@payment_type = 'CODE3' OR @payment_type = 'CODE4')
SET @myBool12 = 1
ELSE
SET @myBool12 = 0

SELECT
SUM(Mydatabase.dbo.[PAYMENTS].[AMT_RECD])
FROM Mydatabase.dbo.[PAYMENTS]
INNER JOIN Mydatabase.dbo.[ACCT]
ON Mydatabase.dbo.[PAYMENTS].[SOME_UID] = Mydatabase.dbo.[ACCT].[SOME_UID]
WHERE Mydatabase.dbo.[ACCT].[CLIENT] = 'MY CLIENT'
AND Mydatabase.dbo.[PAYMENTS].[DATE_RECD] = @mydate
AND Mydatabase.dbo.[PAYMENTS].[BOOL] = @myBool1
AND Mydatabase.dbo.[PAYMENTS].[SOURCE] != 'val1'
AND Mydatabase.dbo.[PAYMENTS].[SOURCE] != 'val2'
AND Mydatabase.dbo.[PAYMENTS].[SOURCE] != 'val3'

IF (@payment_type = 'CODE3' OR @payment_type = 'CODE4')
BEGIN
AND Mydatabase.dbo.[PAYMENTS].[SOURCE] != 'val4'
AND Mydatabase.dbo.[PAYMENTS].[SOURCE] != 'val5'
END
END
GO

SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO



View 4 Replies View Related

Try.. Catch Block

Dec 11, 2006

HI,
i'm trying to execute some sql using the Try.. Catch blocks.

Following code does not execute in Catch Block

Begin
begin try
insert into dbo.Test values (1,'aaa')
-- here we are inserting int value in identity field...
END TRY
Begin catch
PRINT 'TEST'
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;
END Catch
End
GO


Whereas the following block works fine and the Catch block executes.

Begin
begin try
Select 1/0
--This causes an error.
END TRY
Begin catch
PRINT 'TEST'
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;
END Catch
End
GO





Any idea why is it so?

View 5 Replies View Related

Try Catch Block

Apr 12, 2006

Hi:

one of our study group members noticed a strange behavior and has the following question. Any thoughts are appreciated.
I am unable to understand as to why the CATCH block is not executed when an INSERT is made
On table T3 which is dropped after the first transaction.

The severity of Insert into t3 values (3) is Msg 208, Level 16, State 1, Line 2
Invalid object name 't3'.

BOL says TRY€¦CATCH constructs do not trap the following conditions:
Warnings or informational messages with a severity of 10 or lower.
Errors with severity of 20 or higher that terminate the SQL Server Database Engine task processing for the session. If an error occurs with severity of 20 or higher and the database connection is not disrupted, TRY€¦CATCH will handle the error.


Here is the script.




use tempdb
go

create table t1 (a int)
create table t2 (b int)
create table t3 (c int)


Begin tran

Insert into t1 values (1)
Insert into t2 values (2)
Insert into t3 values (3)

IF @@error <> 0
Rollback tran
else
commit tran
-------------------------------------------------------------

Select * from t1
Select * from t2
Select * from t3
-------------------------------------------------------------

Drop table t3

-------------------------------------------------------------

Set xact_abort on
Begin try
Begin tran insertNow

Insert into t1 values (1)
Insert into t2 values (2)

save tran insertNow

Insert into t3 values (3)
commit tran insertNow
End try

Begin Catch

IF (XACT_STATE()) = -1
BEGIN
PRINT 'The transaction is in an uncommittable state.' +
' Rolling back transaction.'
ROLLBACK TRANSACTION insertNow
END;

-- Test if the transaction is active and valid.
IF (XACT_STATE()) = 1
BEGIN
PRINT 'The transaction is committable.' +
' Committing transaction.'
COMMIT TRANSACTION insertNow
END

End Catch



View 9 Replies View Related

Begin End - Not Executed

May 14, 2008

hello, I have a big problem with a script.. some instructions seems to be not executed. I don't understand. If I execute line perline it's ok - but the entire block no.
Explain me and find the solution:

IF NOT EXISTS ( SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'ACS_ACL'
AND COLUMN_NAME = 'ZoneUId' )
BEGIN

ALTER TABLE dbo.ACS_ACL ADD ZoneUId T_UID;

UPDATE dbo.ACS_ACL SET ZoneUId = '1' WHERE ZoneUId IS NULL;


print 'end of script'

END



result:

Msg 207, Level 16, State 1, Line 9
Invalid column name 'ZoneUId'.

the error is on line:
UPDATE dbo.ACS_ACL SET ZoneUId = '000000001' WHERE ZoneUId IS NULL;

how is is possible because the preceding line is

ALTER TABLE dbo.ACS_ACL ADD ZoneUId T_UID;

View 9 Replies View Related

Transactions & TRY CATCH Block.

Oct 10, 2006

Can anyone give a template for a stored procedure which involves a transaction and has a TRY CATCH block too...

Thanks in advance.

View 1 Replies View Related

TRY..CATCH Block Not Cetching RAISERROR()

Sep 30, 2007

 I guess this is a common problem because I ran into a lot of threads concerning the matter. Unfortunately, none of them helped my situation.I am throw a RAISERROR() in my sql and my vb.net try catch block is not detecting an error. SELECT '3'
RAISERROR('testerror',10,5)  Dim con As New SqlConnection Dim _sqlcommand As New SqlCommand con = New SqlConnection(Spiritopedia.Web.Globals.Settings.General.ConnectionString) _sqlcommand.CommandType = Data.CommandType.StoredProcedure _sqlcommand.CommandText = "TestFunction"
_sqlcommand.Connection = con


'The value to be returned
Dim value As New Object
'Execute the command making sure the connection gets closed in the end

Try

'Open the connection of the command
_sqlcommand.Connection.Open()
'Execute the command and get the number of affected rows 'value = _sqlcommand.ExecuteScalar().ToString()

value = _sqlcommand.ExecuteScalar()


Catch ex As SqlException Throw ex Finally

'Close the connection
_sqlcommand.Connection.Close()
End Try
  

View 6 Replies View Related

Clearing Exception In Catch Block

Sep 3, 2004

Is there any way to clear out the exception from a previous Try/Catch block if I am nesting another Try/Catch block within it. I am executing a SQL Command and based on the Error number coming back decide whether or not to execute various other Sql commands. Now the Outer exception seems to be taking precedence over the Inner try block, and even though the code is stepped through for the inner try block it is never executed due to the Parent Exception. Is there any way to clear the exception received from the outer Try block? Here is a snippet of code:


Try

Cmd = New SqlCommand(Sql, Con)

Cmd.ExecuteNonQuery()

Catch t as SqlException

if t.Number = "2601" then

sql_upd = "<Text>"

Try

Cmd_upd = New SqlCommand(Sql_upd, Con)

Cmd_upd.ExecuteNonQuery()

Catch b as Exception

response.write("<Text>")

End Try

End If

End Try
Thanks,

View 3 Replies View Related

T-SQL (SS2K8) :: Try Catch Block In While Loop

Feb 25, 2015

I encountered a werid bug that I can't figure it out in my stored procedure.Here's some sample code the can represent the scenario

Create Proc sp_test
@DeptID Int
as
Begin
Declare @i int=0
Declare @Count int=(Select count(*) from Total)
while(@i<@Count)

[code]....

In the above code Total is a table that has employee name and its department ID and row_number info.The above code should list all employee info that belongs to one DEpt.but after I placed a try catch block the select statement returns no records.If I removed the try catch block it behaves correct.For example If three records reside in the Total table for a certain DeptID.

I expect the outPut will be
Name age salary
Mike 35 $60006
Tom 50 $75000
Frank 55 $120000

View 6 Replies View Related

TRY...CATCH Block Not Working Properly

May 25, 2008

Can someone please help me figure out why this trigger causes a "Timeout expired" error after the first try? What I'm trying to do is create an incrementing default value for the projectid field. I have a unique index on the field and for some reason, the INSERT statement won't run inside the TRY block, even though the WHILE loop creates a unique id. It's acting like the loop isn't incrementing, but the PRINT statements prove that the loop does work, but the INSERT statement doesn't work after a succesful first try (i.e. NEWPROJ-1 is inserted correctlly). Anyways, any help would be appreciated.





Code Snippet
GO
/****** Object: Trigger [Projects].[CreateID] Script Date: 05/25/2008 14:16:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [Projects].[CreateID]
ON [Projects].[tblProjects]
INSTEAD OF INSERT
AS
DECLARE @projectid varchar(25)
DECLARE @projectname varchar(100)
DECLARE @projectepskey int
DECLARE @maxcount int
SELECT @maxcount = 1

BEGIN
SET NOCOUNT ON;
SELECT @projectname = projectname
FROM inserted
SELECT @projectepskey = projectepskey
FROM inserted

SELECT projectid
FROM Projects.tblProjects
WHERE (projectid = 'NEWPROJ')

IF (@@RowCount = 0)
BEGIN
SELECT @projectid = 'NEWPROJ'
INSERT INTO Projects.tblProjects(projectepskey, projectid, projectname)
VALUES
(@projectepskey, @projectid, @projectname)
END
ELSE
BEGIN
WHILE @maxcount >= 1
BEGIN

BEGIN TRY
SELECT @projectid = 'NEWPROJ-' + CONVERT(varchar, @maxcount)
PRINT @projectid
INSERT INTO Projects.tblProjects(projectepskey, projectid, projectname)
VALUES
(@projectepskey, @projectid, @projectname)
BREAK
END TRY
BEGIN CATCH
SELECT @maxcount = @maxcount + 1
PRINT CONVERT(varchar, @maxcount)
CONTINUE
END CATCH;
END
END
END









View 4 Replies View Related

Rollback Doesnt Work In Begin Try ---catch

Nov 10, 2006



Hi ,



In the below procedure in emp table name column is not null.

so when i try to update null value it should rollback previous transactions and should not commit.

but it is updating the previous queries and raising error on 3rd query. not rolliing back. I need to rollback previous queries.

the xactstate i get here is 1.

Please help me with this.



ALTER PROCEDURE [dbo].[tran]

AS

BEGIN

SET NOCOUNT ON;

BEGIN TRY

BEGIN TRANSACTION

declare @name varchar(50)

set @name = null

update dept set dname='ddd' where id=10

update emp set name='eee' where id=354

update emp set name=@name where id=354

COMMIT TRANSACTION



END TRY

BEGIN CATCH

IF (XACT_STATE())=-1 ROLLBACK TRANSACTION

END CATCH

END



venp---

Hi ,



View 6 Replies View Related

T-SQL (SS2K8) :: Catch Block With GOTO Statement?

Mar 6, 2014

I have a Stored Proc which populates a table and then uses BCP to output the table into a flat file and lastly ftp the file out to a remote site.

I'm trying to update the error handling as I first wrote this script on SQL2000 and it has now moved to SQL2008r2. The stored proc looks something like this:

BEGIN TRY
BEGIN TRANSACTION
<A whole bunch of inserts and updates>
COMMIT TRANSACTION
END TRY
BEGIN CATCH
<Error handling>
ROLLBACK TRANSACTION
END CATCH
BEGIN
<xp_cmdshell, BCP, FTP stuff>
END

What I need to do is jump to the end of the script if an error invokes the CATCH block, so the xp_cmdshell stuff is not exicuted. Can I simply put a GOTO statement to take it to the end in the CATCH block, or do I have to set a variable in the CATCH block then test the variable outside the CATCH block or indeed is there a better way to simply terminate the script following the ROLLBACK?

[URL]

View 7 Replies View Related

Raising Errors In A Catch Block In SQL2005

May 3, 2006

When a catchable error occurs in a try block, control is passed to theassociated catch block. While I am then able to examine properties ofthe error using such functions as ERROR_NUMBER() in the catch block,the error-logging scheme used in my company requires that the actualerror be raised so that it can be picked up by components in the nexttier. I appear to be unable to do that -- I can raise some other errorthat has all of the properties of the original except the error number.For example, division by zero raises error 8134. If the code thatproduces that error is enclosed in a try block, I seem to be unable toraise that error from the catch block. Of course, if I never used thetry block to begin with this wouldn't be a problem, but then wewouldn't have the advantages of this structure as it applies to othererrors, some of which we may wish to handle differently. WhileTry-Catch looks great as a way of allowing us to handle errors in acustomized way and to avoid having all errors be passed up to ourmiddle tier, it seems that we are unable to pass ANY such errorsforward, and that is a problem for us, too. Is my understanding ofthis situation correct, or is there some way around this problem, e.g.,is there any way I could have raised error 8134, in the above example?Thanks.

View 2 Replies View Related

Why The Try/Catch Block Cannot Capture This Kind Of Deadlock?

Feb 26, 2008

Hi everybody:

I wanted to handle with the deadlock issue by using Try/Catch, the the try/Catch block cannot capture this kind of deadlock:


code in connection1:
declare @i int
set @i = 0
WHILE (1=1)
begin
ALTER PARTITION SCHEME PartationedTableA NEXT USED [PRIMARY]
ALTER PARTITION FUNCTION PartationedTableA () SPLIT RANGE (14661)
ALTER PARTITION FUNCTION PartationedTableA () MERGE RANGE (14661)
end


code in connection2:
declare @rowcount int
while 1=1
begin

begin try
select @rowcount =count(0) from PartationedTableA where col1=50021
end try
begin catch
print error_number()
end catch
end

run them at the same time in SSMS, the code in cn2 would get a error in several seconds:
Msg 1205, Level 13, State 55, Line 10
Transaction (Process ID 52) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

I tried using TRY/CATCH to capture anoter deadlock whose Error_State is 45, and it works fine.

Does anybody know why Try/Catch cannot capture my deadlock, does the different state make senses?

Thanks.


View 7 Replies View Related

Begin Tran In An Sp Executed Fom Within A Transaction Scope

Jan 28, 2008

we have an update sp that must call an insert sp after the update. The update and insert must act like a transaction, ie all or none.

We believe that wrapping most of the update (including call to insert sp) sp in a begin tran block would guarantee the all or none behavior.

However, we're not sure what would happen if one of our developers calls the update sp from within a transaction scope that expects yet something additional to be included in the transaction. Would the begin tran block (assuming no errors in that block) in the sp commit both the update and insert regardless of what happens in the rest of the .net tran scope?

View 2 Replies View Related

FormView - Update Process Completes With No Error But Records Is Not Changed

Jul 24, 2006

Greetings,
I have setup a FormView which functions as it should but after the user input is updated, the table record stays unchanged, and when I trap the FormView1_ItemUpdated and look at the SqlDataSource1.UpdateCommand, it shows this:
UPDATE [aspnet_test] SET first_name = '', last_name = '', email = '' WHERE id = @original_ID
Here is most of the code I am using:<asp:FormView ID="FormView1" runat="server"   DataSourceID="SqlDataSource1" DataKeyNames="id, first_name, last_name"   OnItemUpdating="FormView1_ItemUpdating" OnItemUpdated="FormView1_ItemUpdated" > .. // my ItemEditTempate is here.</asp:FormView>
<EditItemTemplate>First Name: <asp:TextBox Text='<%# Bind("first_name") %>' runat="server" ID="author_name" Columns="20"></asp:TextBox><br />Last Name: <asp:TextBox Text='<%# Bind("last_name") %>' runat="server" ID="TextBox1" Columns="20"></asp:TextBox><br />E-mail: <asp:TextBox Text='<%# Bind("email") %>' runat="server" ID="TextBox2" Columns="20"></asp:TextBox><br /><br /><asp:Button ID="UpdateButton" runat="server" Text="Update" CommandName="Update" /><asp:Button ID="CancelButton" runat="server" Text="Cancel" CommandName="Cancel" /> </EditItemTemplate>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ASPNETDBConnectionString1 %>"
SelectCommand="SELECT id, first_name, last_name, email FROM aspnet_test where id = 1"UpdateCommand="UPDATE [aspnet_test] SET first_name = '<%# first_name %>',   last_name = '<%# last_name %>',   email = '<%# email %>'   WHERE id = @original_ID ">
<UpdateParameters><asp:Parameter Name="original_ID" Type="Int32" /></UpdateParameters></asp:SqlDataSource>
Any idea where the @original_ID is supposed to get its value from, or why does the SQL command shows blank fields?Thanks
Eric.

View 3 Replies View Related

Error Access Is Denied.. Occurs After Package Successfully Completes.

Jun 4, 2007

I am getting an 'Access is denied' error:

Error 0x80070005 while loading package file "E:SSISPackagesPackage1.dtsx". Access is denied. .

The package is executed from the main package via an 'Execute Package Task' that is within a 'For Each Loop' container. The 'For each loop' goes through a single iteration as expected. The strange thing is that the error comes after 'Package1' has run successfully. I am logging the PackageStart/PackageEnd and error events and I see that Package1 ends successfully and then the "Access is denied" error occurs. The main package is launched by executing dtsexec via Process.Start() from a web page. The packages have 'SaveCheckpoints' set to True. Any ideas are welcome. Thanks.

View 7 Replies View Related

Try Catch Doesn't Catch Errors Inside A Data Flow Transformation Script Component

Feb 15, 2007

Hi,

I'm having trouble with a Script Component in a data flow task. I have code that does a SqlCommand.ExecuteReader() call that throws an 'Object reference not set to an instance of an object' error. Thing is, the SqlCommand.ExecuteReader() call is already inside a Try..Catch block. Essentially I have two questions regarding this error:

a) Why doesn't my Catch block catch the exception?
b) I've made sure that my SqlCommand object and the SqlConnection property that it uses are properly instantiated, and the query is correct. Any ideas on why it is throwing that exception?

Hope someone could help.

View 3 Replies View Related

T-SQL (SS2K8) :: Why Block Scope Variables Exist Outside Of Block

Dec 3, 2014

I have the following stored procedure to test scope of variables

alter proc updatePrereq
@pcntr int,
@pmax int
as
begin

[Code] ....

In the above script @i is declare in the if block only when the @pcntr value is 1. Assume the above stored procedure is called 5 times from this script

declare @z int
set @z = 1
declare @max int
set @max = 5
while @z <= @max
begin
exec dbo.updatePrereq @z, @max
set @z = @z + 1
end
go

As i said earlier `@i` variable exists only when `@pcntr` is `1`. Therefore when i call the stored procedure for the second time and so forth the control cannot enter the if block therefore @i variable wouldn't even exist. But the script prints the value in `@i` in each iteration, How comes this is possible should it throw an error saying `@i` variable does not exist when `@pcntr` values is greater than `1`?

View 1 Replies View Related

Attempt To Catch Error Using @@ERROR In SQL 2000 Is Failing

May 2, 2007

We have a stored procedure that calculates the floor nr for users at our company campus using their office location. The calculation is done by a function that returns an integer. Unfortunately, not all users enter their information correctly so the function sometimes raises an error. Below is the code of that stored procedure.



UPDATE PERSONS

SET FLOORNR = dbo.FloorNR(OFFICELOCATION)

WHERE OFFICELOCATION IS NOT NULL



IF(@@ERROR <> 0 OR @@ROWCOUNT = 0)

BEGIN

RAISERROR ('Failed to calculate the floor number', 16, 1 ) with nowait

END



However, when the function dbo.FloorNR fails, it doesn't raise our error, but it seems to raise the error that comes from dbo.FloorNR.



How can we catch errors that come from dbo.FloorNr so that we can raise our own error? Our company still uses SQL 2000, so we cannot use the SQL 2005 try/catch option.

View 3 Replies View Related

Syntax Error With Begin Try MSG 156

Feb 29, 2008

I get a syntax error when trying to use BEGIN TRY / END TRY in a SQL Server 2005 stored procedure.

I've checked the compatability of the database and its SQL Server 2005 (90). I'm creating the stored procedure in SSMS 2005. Any thoughts would be appreciated, thanks.

View 2 Replies View Related

SP Catch Error

Aug 21, 2007

Hi,

I have the following stored procedure which is added to the windows scheduler. When it is run I'm getting an "Invalid use of null error", therefore I need to capture and any errors but I'm not sure how to do this. Can someone help?
Thanks.


Code:

CREATE PROCEDURE [dbo].[usp_Reminders] AS

DECLARE @ReminderSent datetime
DECLARE @getRecords CURSOR
DECLARE @err int

SELECT E.[RL Staff No], E.Forename, E.Surname, C.CourseName, V.CourseDate , E.Email, V.ReminderSent
FROM empdetails.dbo.v_Employee E
INNER JOIN Validation V ON E.[RL Staff No] = V.[RL Staff No]
INNER JOIN empdetails.dbo.v_Course C ON V.CourseCode = C.CourseCode
WHERE V.Completed Is Null AND V.ReminderSent Is Null AND V.CourseDate <= dateadd(dd, -3, getdate())
order by e.[rl staff no]

SET @getRecords = CURSOR FOR

SELECT V.ReminderSent
FROM empdetails.dbo.v_Employee E
INNER JOIN Validation V ON E.[RL Staff No] = V.[RL Staff No]
INNER JOIN empdetails.dbo.v_Course C ON V.CourseCode = C.CourseCode
WHERE V.Completed IS NULL AND V.ReminderSent IS NULL AND V.CourseDate <= dateadd(dd, -3, getdate())
ORDER BY e.[rl staff no]

OPEN @getRecords
FETCH NEXT FROM @getRecords INTO @ReminderSent
WHILE @@FETCH_STATUS= 0
BEGIN
UPDATE Validation
SET ReminderSent = GetDate()
WHERE CURRENT OF @getRecords
FETCH NEXT FROM @getRecords INTO @ReminderSent
END

CLOSE @getRecords
DEALLOCATE @getRecords
GO

View 1 Replies View Related

Error Catch In SQL

Jul 20, 2005

Hi everyone, I am using an SQL extended stored procedure to send emails in aDTS package using a cursor that goes through each row in a table.Email sending code below======================exec master.dbo.xp_smtp_sendmail@FROM = @sFrom,@FROM_NAME = @sFrom,@TO = @sRecepients,@subject = @sSubject,@message = @sBody,@type = N'text/html',@codepage = 0,@server =N'MYMAILSERVER'======================Fetch Next From EmailCursor ...Now the problem I have is that if an individual email address in invalidthen an error occurs and the whole DTS package falls over. What I would liketo be able to do is "catch the error", something like this (C# code used asexample)try{exec master.dbo.xp_smtp_sendmail@FROM = @sFrom,@FROM_NAME = @sFrom,@TO = @sRecepients,@subject = @sSubject,@message = @sBody,@type = N'text/html',@codepage = 0,@server =N'MYMAILSERVER'} catch {exec master.dbo.xp_smtp_sendmail@FROM = "arealaddress@mybusiness.com",@FROM_NAME = @sFrom,@TO = @sRecepients,@subject = @sSubject,@message = @sBody,@type = N'text/html',@codepage = 0,@server =N'MYMAILSERVER'}Is this possible??? Normally I would do all the email validation before theemail is entered into the database but unfortunately, I do not have accessto the application code so I am stuck doing it this way.Thanks in advanceMark

View 2 Replies View Related

FTP Task Variable Does Not Begin With '/' Error

Sep 5, 2006

I created a ftp task that uses a variable for the remote path because the file I download changes names every based on the date. So I build up the entire path into a container variable and set the remote path to a variable. then I get an error that the filename does not begin with '/' when the filename that the error references is my variable... I cannot even debug/build my package cause of this error. I cannot find anything online or in BOL. any help would be appriciated. If you need more info to help let me know also.

My variable is set as a string,

exact error:

Error 1 Validation error. Get DailyFiles FTP Task: Variable "DailyFiles" doesn't start with "/". DAILY.dtsx 0 0




Thanks in advance.

View 3 Replies View Related

Same DTS Fails Executed As Job ,but Run Fine When Executed From DTS Designer

Mar 13, 2002

I created DTS a while ago and placed in job to run once a day (it worked fine for 3 months)
2 days ago I changed sa password and now job fails with error (Login failed for user 'sa'.), but it run fine from DTS !!!


1. My DTS created with domain Account DomainSVCSQL2000( sa rights and local admin)
2. SVCSQL service use DomainSVCSQL2000 to run
3. SVCSQL agent use DomainSVCSQL2000 to run
4. DTS use 'osql -E

Where should look for reference to sa ?







Executed as user: MONTREALsvcsql2000. DTSRun: Loading... Error: -2147217843 (80040E4D); Provider Error: 18456 (4818) Error string: Login failed for user 'sa'. Error source: Microsoft OLE DB Provider for SQL Server Help file: Help context: 0. Process Exit Code 1. The step failed.

View 5 Replies View Related

Error Handling With Try/catch

Feb 6, 2008

Hey,Here's yet another question for you more knowledgeable than me Up to this point I have been using a try/catch statement when dealing with SQL, for exampleint result = 0;try{result = Int32.Parse(command.ExecuteScalar().ToString());}catch{result = 0;}But I read up one some error handling and I have no idea how to solve this anymore. Since I'll be using the catch block to catch exceptions, something like thiscatch (SqlException){throw;}So I was wondering what is the good, standard practice for dealing with this since I need the catch statement to set result to zero or I would end up with an error.Thanks in advance,Sixten 

View 2 Replies View Related

SP Error Handling And Try/Catch

May 9, 2006

I'm looking for a discussion of the pros and cons of using TRY/CATCH as an error handler in a standard fashion with Stored Procedures.  I've been using SQL Server for some time, and am accustomed to an approach of error handling in SPs that returns control from an SP via a common exit routine. 

Has anyone defined an approach they would consider sharing?  I realize that the reasons for standardizing on an approach includes requirements to your specific situation, so there are likely no perfect answers.  I understand the basics of TRY/CATCH in SQL Server. Specifically, I'm looking for an approach where a common "Catch Handler" is used, paying attention to the issues around COMMIT/ROLLBACK.

If there are any threads that discuss this, let me know; I've performed a seach and found nothing so far.

Thanks,

Chuck

View 4 Replies View Related

BEGIN STACK DUMP Error In Log Viewer

Dec 5, 2006

Hi

We are having problems with our application that uses SQL Server 2005 in a cluster environment. Sometimes the system stops answering and registers in the log viewer the following error:

=====================================================================
BugCheck Dump
=====================================================================

This file is generated by Microsoft SQL Server
version 9.00.1399.06
upon detection of fatal unexpected error. Please return this file, the query or program that produced the bugcheck, the database and the error log, and any other pertinent information with a Service Request.

Computer type is AT/AT COMPATIBLE.
Bios Version is IBM - 1001
Current time is 16:48:36 12/05/06.
2 Intel x86 level 15, 3600 Mhz processor (s).
Windows NT 5.2 Build 3790 CSD Service Pack 1.

Memory
MemoryLoad = 74%
Total Physical = 3327 MB
Available Physical = 858 MB
Total Page File = 9318 MB
Available Page File = 7058 MB
Total Virtual = 2047 MB
Available Virtual = 274 MB
**Dump thread - spid = 132, PSS = 0x71E09588, EC = 0x71E09590
***Stack Dump being sent to E:Microsoft SQL ServerMSSQL.1MSSQLLOGSQLDump0178.txt
* *******************************************************************************
*
* BEGIN STACK DUMP:
* 12/05/06 16:48:36 spid 132
*
* Location: lckmgr.cpp:10820
* Expression: GetLocalLockPartition () == xactLockInfo->GetLocalLockPartition ()
* SPID: 132
* Process ID: 2436
*
* Input Buffer 255 bytes -
* „ 16 00 00 00 12 00 00 00 02 00 01 00 00 00 84 00 00 00
* ÿÿ çd � 01 00 00 00 ff ff 0a 00 02 00 00 00 e7 64 09 09 04 d0
* 4d S E L E C T 00 34 64 09 20 00 53 00 45 00 4c 00 45 00 43 00 54 00
* TAbleA (*) 20 00 54 00 48 00 69 00 73 00 74 00 6f 00 72 00 69 00

(*) There is a query here that I have excluded in the message

*
* MODULE BASE END SIZE
* sqlservr 01000000 02BA7FFF 01ba8000
* ntdll 7C910000 7C9D3FFF 000c4000
* kernel32 7C800000 7C90BFFF 0010c000
* MSVCR80 78130000 781CAFFF 0009b000
* msvcrt 77B90000 77BE9FFF 0005a000
* MSVCP80 7C420000 7C4A6FFF 00087000
* ADVAPI32 77D90000 77E3DFFF 000ae000
* RPCRT4 77C40000 77CDEFFF 0009f000
* USER32 77F40000 77FD1FFF 00092000
* GDI32 77BF0000 77C37FFF 00048000
* CRYPT32 760D0000 76164FFF 00095000
* MSASN1 760B0000 760C1FFF 00012000
* Secur32 76E70000 76E82FFF 00013000
* MSWSOCK 71970000 719B1FFF 00042000
* WS2_32 71A50000 71A66FFF 00017000
* WS2HELP 71A40000 71A47FFF 00008000
* USERENV 76840000 76904FFF 000c5000
* opends60 333E0000 333E6FFF 00007000
* NETAPI32 71A90000 71AE7FFF 00058000
* SHELL32 7C9E0000 7D1EAFFF 0080b000
* SHLWAPI 77EE0000 77F31FFF 00052000
* comctl32 77360000 77462FFF 00103000
* EntApi 37000000 37012FFF 00013000
* PSAPI 76A90000 76A9AFFF 0000b000
* WININET 779D0000 77A78FFF 000a9000
* OLEAUT32 77CF0000 77D7BFFF 0008c000
* ole32 77510000 77643FFF 00134000
* instapi 48060000 48069FFF 0000a000
* CLUSAPI 74CF0000 74D01FFF 00012000
* RESUTILS 74E00000 74E12FFF 00013000
* sqlevn70 4F610000 4F7A0FFF 00191000
* SQLOS 344D0000 344D4FFF 00005000
* rsaenh 68000000 6802EFFF 0002f000
* AUTHZ 76B60000 76B73FFF 00014000
* MSCOREE 340C0000 34104FFF 00045000
* msv1_0 76BB0000 76BD6FFF 00027000
* iphlpapi 76C10000 76C29FFF 0001a000
* kerberos 34330000 34387FFF 00058000
* cryptdll 76600000 7660BFFF 0000c000
* schannel 76670000 76696FFF 00027000
* COMRES 76F30000 770BCFFF 0018d000
* XOLEHLP 343F0000 343F5FFF 00006000
* MSDTCPRX 34400000 34477FFF 00078000
* msvcp60 780C0000 78120FFF 00061000
* MTXCLU 74E50000 74E68FFF 00019000
* VERSION 77B80000 77B87FFF 00008000
* WSOCK32 71A00000 71A09FFF 0000a000
* DNSAPI 76DF0000 76E1EFFF 0002f000
* winrnr 76E90000 76E96FFF 00007000
* WLDAP32 76E30000 76E5EFFF 0002f000
* rasadhlp 76EA0000 76EA7FFF 00008000
* hnetcfg 36190000 361E8FFF 00059000
* wshtcpip 71930000 71937FFF 00008000
* security 36340000 36343FFF 00004000
* msfte 36A60000 36CB7FFF 00258000
* dbghelp 36D00000 36E17FFF 00118000
* WINTRUST 76AD0000 76AFAFFF 0002b000
* imagehlp 76B30000 76B58FFF 00029000
* dssenh 68100000 68123FFF 00024000
* NTMARTA 777B0000 777D1FFF 00022000
* SAMLIB 36FE0000 36FEEFFF 0000f000
* ntdsapi 76610000 76624FFF 00015000
* xpsp2res 61BF0000 61EBFFFF 002d0000
* CLBCatQ 77650000 776D2FFF 00083000
* sqlncli 61EC0000 620E1FFF 00222000
* COMCTL32 77E40000 77ED6FFF 00097000
* comdlg32 761D0000 76218FFF 00049000
* SQLNCLIR 007C0000 007F2FFF 00033000
* msftepxy 621F0000 62204FFF 00015000
* xpsqlbot 62860000 62865FFF 00006000
* xpstar90 62880000 628C4FFF 00045000
* SQLSCM90 628E0000 628E8FFF 00009000
* ODBC32 62900000 6293CFFF 0003d000
* BatchParser90 62940000 6295DFFF 0001e000
* SQLSVC90 62970000 62989FFF 0001a000
* SqlResourceLoader 629A0000 629A5FFF 00006000
* ATL80 7C630000 7C64AFFF 0001b000
* odbcint 62B00000 62B17FFF 00018000
* SQLSVC90 62B20000 62B22FFF 00003000
* xpstar90 62B30000 62B55FFF 00026000
* xplog70 62B60000 62B6BFFF 0000c000
* xplog70 62B80000 62B82FFF 00003000
* oledb32 631B0000 63228FFF 00079000
* MSDART 63230000 63249FFF 0001a000
* OLEDB32R 634D0000 634E1FFF 00012000
* activeds 76D10000 76D42FFF 00033000
* adsldpc 76CE0000 76D06FFF 00027000
* credui 76AA0000 76ACDFFF 0002e000
* ATL 769A0000 769B7FFF 00018000
* adsldp 71110000 7113DFFF 0002e000
* SXS 75CB0000 75D6BFFF 000bc000
* dbghelp 65D40000 65E52FFF 00113000
*
* Edi: 6610BCB8: 636A1900 3E3A6040 62F1A040 6610D8AD 0279E900 3E3A63D8
* Esi: 00000000:
* Eax: 6610BB9C: 000042AC 00000000 00000000 7C815E02 00000000 7C931B34
* Ebx: 0000003F:
* Ecx: 6610C20C: 00000000 00010007 00000000 00740072 636A1904 6610BBCC
* Edx: 0000003D:
* Eip: 7C815E02: 10C2C95E 90909000 A1649090 00000018 C334408B 891C428B
* Ebp: 6610BBEC: 6610BC30 02172CE4 000042AC 00000000 00000000 00000000
* SegCs: 0000001B:
* EFlags: 00000246:
* Esp: 6610BB98: 71E09588 000042AC 00000000 00000000 7C815E02 00000000
* SegSs: 78130023: 00000000 00000000 00000000 00000000 00000000 00000000
* *******************************************************************************
* -------------------------------------------------------------------------------
* Short Stack Dump
7C815E02 Module(kernel32+00015E02)
02172CE4 Module(sqlservr+01172CE4)
02176BA0 Module(sqlservr+01176BA0)
02019506 Module(sqlservr+01019506)
015738EE Module(sqlservr+005738EE)
021B15B6 Module(sqlservr+011B15B6)
0163DD36 Module(sqlservr+0063DD36)
010E9FA3 Module(sqlservr+000E9FA3)
010B0F5F Module(sqlservr+000B0F5F)
0102C5F8 Module(sqlservr+0002C5F8)
01BEE12B Module(sqlservr+00BEE12B)
01BF2BCB Module(sqlservr+00BF2BCB)
01BF353D Module(sqlservr+00BF353D)
010438E5 Module(sqlservr+000438E5)
01041C35 Module(sqlservr+00041C35)
0100889F Module(sqlservr+0000889F)
010089C5 Module(sqlservr+000089C5)
010086E7 Module(sqlservr+000086E7)
010D764A Module(sqlservr+000D764A)
010D7B71 Module(sqlservr+000D7B71)
010D746E Module(sqlservr+000D746E)
010D83F0 Module(sqlservr+000D83F0)
781329AA Module(MSVCR80+000029AA)
78132A36 Module(MSVCR80+00002A36)

PSS @0x71E09588
---------------

CSession @0x71E08278
--------------------
m_spid = 132 m_cRef = 12 m_rgcRefType[0] = 1
m_rgcRefType[1] = 1 m_rgcRefType[2] = 9 m_rgcRefType[3] = 1
m_rgcRefType[4] = 0 m_rgcRefType[5] = 0 m_pmo = 0x71E08040
m_pstackBhfPool = 0x00000000 m_dwLoginFlags = 0x03e0 m_fBackground = 0
m_fClientRequestConnReset = 0 m_fUserProc = -1 m_fConnReset = 0
m_fIsConnReset = 0 m_fInLogin = 0 m_fReplRelease = 0
m_fKill = 0 m_ulLoginStamp = 3105683 m_eclClient = 5
m_protType = 5 m_hHttpToken = FFFFFFFF

m_pV7LoginRec
---------------------
00000000: 18010000 02000972 401f0000 00000006 400c0000 € .......r@.......@...
00000014: 00000000 e0030000 00000000 00000000 5e000400 € ................^...
00000028: 66000200 6a000000 7a001c00 b2000c00 ca000000 € f...j...z...........
0000003C: ca001c00 02010000 02010b00 60f120db ad481801 € ............`. ..H..
00000050: 00001801 00001801 00000000 0000€ € € € € € € € € € € € € € € ..............

CPhysicalConnection @0x71E08188
-------------------------------
m_pPhyConn->m_pmo = 0x71E08040 m_pPhyConn->m_pNetConn = 0x71E08788 m_pPhyConn->m_pConnList = 0x71E08260
m_pPhyConn->m_pSess = 0x71E08278 m_pPhyConn->m_fTracked = -1 m_pPhyConn->m_cbPacketsize = 8000
m_pPhyConn->m_fMars = 0 m_pPhyConn->m_fKill = 0

CBatch @0x71E08A90
------------------
m_pSess = 0x71E08278 m_pConn = 0x71E089F0 m_cRef = 3
m_rgcRefType[0] = 1 m_rgcRefType[1] = 1 m_rgcRefType[2] = 1
m_rgcRefType[3] = 0 m_rgcRefType[4] = 0 m_pTask = 0x006F9D38

EXCEPT (null) @0x6610B4AC
-------------------------
exc_number = 0 exc_severity = 0 exc_func = 0x023D96B0

Task @0x006F9D38
----------------
CPU Ticks used (ms) = 1 Task State = 2
WAITINFO_INTERNAL: WaitResource = 0x00000000 WAITINFO_INTERNAL: WaitType = 0x0
WAITINFO_INTERNAL: WaitSpinlock = 0x00000000 SchedulerId = 0x0
ThreadId = 0x444 m_state = 0 m_eAbortSev = 0

EC @0x71E09590
--------------
spid = 132 ecid = 0 ec_stat = 0x0
ec_stat2 = 0x40 ec_atomic = 0x4 __fSubProc = 1
ec_dbccContext = 0x00000000 __pSETLS = 0x71E08A30 __pSEParams = 0x71E08CD0
__pDbLocks = 0x71E09878

SEInternalTLS @0x71E08A30
-------------------------
m_flags = 0 m_TLSstatus = 3 m_owningTask = 0x006F9D38
m_activeHeapDatasetList = 0x71E08A30 m_activeIndexDatasetList = 0x71E08A38


SEParams @0x71E08CD0
--------------------
m_lockTimeout = -1 m_isoLevel = 1048576 m_logDontReplicate = 0
m_neverReplicate = 0 m_XactWorkspace = 0x03F78940 m_pSessionLocks = 0x71E09A88
m_pDbLocks = 0x71E09878 m_execStats = 0x3F867018 m_pAllocFileLimit = 0x00000000




Does anybody know what€™s going on?
I will be very appreciate if someone can help me to solve this problem. Thank you!





View 3 Replies View Related

Catch The Error On Insert Or Update (was Need Help)

Jan 5, 2005

hello!

im new to sql... what i'm trying to do is catch the error on insert or update statment of sql.. sound simple but please..

this is the sample table design...

tbl_Customer

CustomerID int(4) Primary AutoIncrement
CustomerCode nvarchar(25)
CustomerName nvarchar(25)
..
..
Deleted bit(1)


what i'm trying to do is when a record is deleted, it's not actually deleted
in the table but only marked 1 (true) the Deleted field.. because i don't want
to lose the relationship...

it's easy to do this on insert statement like this..

Create Procedure InsertCustomer(@param1 ....) AS
IF NOT EXIST (SELECT * FROM tbl_Customer WHERE DELETED = 0) THEN
// do insert statement here
ELSE
// Do nothing

GO

this is also easy if i create a index constraints on the table.. but this will violate my design idea..

so anybody can help me to create the procedure in update statement and insert statement

View 1 Replies View Related

How To Catch Date Conversion Error

Mar 8, 2004

hi,

I try to write a function which includes a statement:

SELECT @dateReturn = CAST(@dateString As datetime)

to convert a string to datetime.

When it runs, sometime it will generate :
"The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value."
and all related are terminated.

Can I find a way to catch this error and don't let it terminate the whole thing? For
example, when this happens, I want to get datetime as NULL instead of just being
terminated.

Thanks.

View 1 Replies View Related

Catch Error Message In Variable?

May 24, 2006

Greetings all,

When an error occurs it is written to a log file (Assuming you have loggin on).
Anyone know of a way to catch the error in a variable?

When an error occurs I send an email explaining where there error happened and to view the logfile. I would like to include the last error in the email. Saves having to go view the log...

Thanks

View 14 Replies View Related

Check Referential Ingerity Or Catch Error

Oct 6, 2004

Hi all,

Just wondering what would be the normal or more efficient practice to insert/update a record.

1. Check for existence of primary record (using SELECT in stored procedure)
2. Capture error and handling

My problem is that I try to execute an stored procedure from a VB client.. but unable to capture the errors in SP, it just prompts the error and thats it, not responding to my "SELECT @err = @@ERROR" after the insert statement.

so now, I'm thinking of capturing the error on the client (which I am able to do) and handle it from there.. or to make sure that RI is enforced by 'searching' for Pks in the primary tables before executing the INSERT statement in my stored procedure.

Any advise would be appreciated..

Cyherus

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved