SQL Server 2008 :: Error Handling In Called Stored Procedures?
Apr 14, 2015
I have one main stored procedure. It calls other 10 stored procedures by giving input parameters.
Do I want to implement Begin Try/Begin catch in each sub procedures or in main procedure only.
View 2 Replies
ADVERTISEMENT
Oct 19, 2015
We're trying to troubleshoot a timeout issue, so it was requested that I add a WAITFOR statement (1 hour) in a certain stored proc our application uses. I added it and confirmed that it was working by executing the stored proc in SSMS.
However, when our application (using Entity Framework) calls the stored proc, the WAITFOR statement is ignored.
View 4 Replies
View Related
Jul 23, 2005
I have a requirement that requires detection of rows deleted/updated byother processes. My business objects call stored procedures to create,read, update, delete data in a SQL Server 2000 data store. I've donea fair amount of research on concurrency handling in newsgroups andother resources. Below is what I've come up as a standard forhandling concurrency thru stored procedures. I am sharing with everyoneso I can get some comments (pro/con) regarding this approach and see ifanyone can find any holes for this solution.Below is the DDL, DML and a Stored Proc demonstrating the approach. Iam using a rowversion column for concurrency checking. Another approachthat is less intrusive (doesn't require having a rowversion column inall tables) is using checksum. I may eventually use checksum but theprocess flow should be almost identical. Looking forward to anyone'scomments.Thx, BZ--xxxxxxxxxxxxxxxxxxxxxxxxxxx--IF EXISTS (SELECT * FROM sysobjects WHERE type = 'U' AND name ='ApplicationUsers')BEGINPRINT 'Dropping Table ApplicationUsers'DROP Table dbo.ApplicationUsersENDGOPRINT 'Creating Table ApplicationUsers'GOCREATE TABLE dbo.ApplicationUsers(LoginName varchar (20) NOT NULL Primary Key,LoginPassword varchar (50) NOT NULL,LoginAttempts int NOT NULL default(0),EmailAddress varchar(25) NOT NULL Unique,DataVersion rowversion NOT NULL)GOIF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name ='UpdateUser')BEGINPRINT 'Dropping Procedure UpdateUser'DROP Procedure dbo.UpdateUserENDGOPRINT 'Creating Procedure UpdateUser'GOCreate Procedure dbo.UpdateUser@loginName Varchar (20),@loginPassword Varchar (50),@loginAttempts Int,@emailAddress Varchar(25),@dataVersion Rowversion OutputAs/************************************************** ****************************** Name: dbo.UpdateUser** Desc: Updates an Application User instance**** Parameters:** Input** @loginName** @loginPassword** @loginAttempts** @emailAddress** @dataVersion. row version used for concurrency control.**** Output** @dataVersion. updated row version used for concurrencycontrol.**** Return** 0 for Success. Error code if any are encountered** 66661 if current row version doesn't match provided version** 66666 if expected row is not found**************************************************** *****************************/Set NoCount OnDeclare@err Int,@rowCount Int,@tranCount Int--Transaction HandlingSelect @tranCount = @@TRANCOUNTIf (@tranCount=0)Begin Tran LocalTranElseSave Tran LocalTranUpdatedbo.ApplicationUsersSetLoginPassword = @loginPassword,LoginAttempts = @loginAttempts,EmailAddress = @emailAddressWhereLoginName = @loginNameAndDataVersion = @dataVersion--Check for errors and rowCount (Should have updated 1 row)Select @err = @@ERROR, @rowCount = @@ROWCOUNTIf (@err != 0) GOTO ErrHandlerIf (@rowCount != 1) GOTO ConcurrencyHandler--Set dataversion output parameterSelect@dataVersion = DataVersionFromdbo.ApplicationUsersWhereLoginName = @loginName/*If we got this far then there were no errorsIf this proc started transaction then commit it,otherwise return and let caller handle transaction*/If (@TranCount = 0)Commit Tran LocalTranReturn 0/*Rollback local transaction if an error was encountered.Return code is used to communicate error number.*/--Handle Concurrency ErrorsConcurrencyHandler:Rollback Tran LocalTranIf Exists (Select * From dbo.ApplicationUsers where LoginName =@loginName)Return 66661 --Row version doesn't match provided versionElseReturn 66666 --Row not found--Handle Other ErrorsErrHandler:Rollback Tran LocalTranReturn @err --Return Err NumberGOPRINT 'Inserting Test Data...'--Add Test DataInsert Into dbo.ApplicationUsers(LoginName, LoginPassword, LoginAttempts, EmailAddress)Values('blackmamba', 'Pwd1', default, 'bm@DIVAS.com')Insert Into dbo.ApplicationUsers(LoginName, LoginPassword, LoginAttempts, EmailAddress)Values('GoGo', 'Pwd2', default, 'gogo@crazy88.com')GO/*Call UpdateUser Stored Proc with current rowversion*/Declare @retVal int, @rowvrsn rowversion--Get Current Row Versionselect @rowvrsn = DataVersion from dbo.ApplicationUsers where LoginName= 'blackmamba'Exec @retVal = dbo.UpdateUser @loginName = 'blackmamba', @loginPassword= 'UpdatedPwd', @loginAttempts = 0, @emailAddress = 'bm@DIVAS.com',@dataVersion = @rowvrsn outputPrint @retVal --Should be 0 for successGO/*Call UpdateUser Stored Proc with out of date rowversion (simulateupdate by other process)*/Declare @retVal int, @rowvrsn rowversion--Get Current Row Versionselect @rowvrsn = DataVersion from dbo.ApplicationUsers where LoginName= 'blackmamba'--Simulate update by other processUpdate dbo.ApplicationUsers Set LoginPassword = LoginPassword whereLoginName = 'blackmamba'--Update User with out of date RowversionExec @retVal = dbo.UpdateUser @loginName = 'blackmamba', @loginPassword= 'UpdatedPwdVersion2', @loginAttempts = 0, @emailAddress ='bm@DIVAS.com', @dataVersion = @rowvrsn outputPrint @retVal --Should be 66661 for rowversion mismatchGO/*Call UpdateUser Stored Proc with out of date rowversion (simulatedelete by other process)*/Declare @retVal int, @rowvrsn rowversion--Get Current Row Versionselect @rowvrsn = DataVersion from dbo.ApplicationUsers where LoginName= 'blackmamba'--Simulate delete by other processDelete From dbo.ApplicationUsers where LoginName = 'blackmamba'--Update User with out of date RowversionExec @retVal = dbo.UpdateUser @loginName = 'blackmamba', @loginPassword= 'UpdatedPwdVersion2', @loginAttempts = 0, @emailAddress ='bm@DIVAS.com', @dataVersion = @rowvrsn outputPrint @retVal --Should be 66666 for row deleted by other process
View 2 Replies
View Related
Feb 12, 2015
I'm looking for an easy way to run all stored procedures in a database that match a specified criteria.
Under normal curcumstances, I'd create a "master" procedure that would call each one in turn using the "EXECUTE" syntax.
As there will be around 140 procedures (there are a few more but they are used for different purposes), I'd like to try and execute them dynamically.
Is there any way of finding out which procedures match the pattern of "usp_merge_*" for the name and executing it?
View 4 Replies
View Related
Mar 5, 2015
I have a column in a table, which have the stored procedure name stored in each row. Now, I need to execute each SP in the table dynamically. I'm trying to construct a SQL but not able to fire them!!
DECLARE @sql VARCHAR(MAX)
SELECT @sql = STUFF((SELECT '; GO EXEC ' + StoredProcedureName + '' FROM MyTable FOR XML PATH ('')),1,5,'')
print @sql
EXEC sp_executesql @sql
View 2 Replies
View Related
Apr 24, 2015
I have this requirement where some store procedures from a "seed" database need to be replicated to another database (on demand, so replication is not suppose to be use in this scenario).
I know it can be achieved by exporting the store procedures and then execute that at the B database but I want something a bit more automatic since it can be a large number of sprocs. I am trying something like this (still in dev):
SET NOCOUNT ON;
--
SELECT ROW_NUMBER() OVER(ORDER BY definition) seq, definition base
into #sprocs
FROM databaseA.[sys].[procedures] p
INNER JOIN databaseA.sys.sql_modules m ON p.object_id = m.object_id
[Code] ....
But I am sure there are way better ways to accomplish that...
View 4 Replies
View Related
Mar 3, 2015
I'm trying to replace a table name in 250 stored procedures. I found this script below which does a good job but it also finds tables with similar names. How can I limit the replacement to the exact table name? If my original table name is MyTable001, I do not want to find MyTable001_ID.
-- set "Result to Text" mode by pressing Ctrl+T
SET NOCOUNT ON
DECLARE @sqlToRun VARCHAR(1000), @searchFor VARCHAR(100), @replaceWith VARCHAR(100)
-- text to search for
SET @searchFor = 'MyTable001'
-- text to replace with
SET @replaceWith = '[MyTable002]'
[code].....
View 0 Replies
View Related
Dec 31, 2004
I've got the folloing stored procedure
ALTER PROCEDURE AddUserData
(@login varchar (8),
@password varchar (8),
@fullName varchar (50),
@RoleID Int,
@statusID Int)
AS
if exists
(SELECT login, @errorReturn
FROM tbEmployee
WHERE login = @login)
return 55555
Else
INSERT INTO tbEmployee (login, password, fullname, RoleID, statusId)
VALUES (@login, @password, @fullName, @RoleID, @statusID)
RETURN @@error
the function that calls this stored procedure is this
Public Shared Function InsertUserData(ByVal login As String, ByVal password As String, ByVal fullName As String, ByVal StatusID As Integer, ByVal RoleID As Integer)
' Create the connection object
Dim connection As New SqlConnection(connectionString)
' Create and initilise the command object
Dim command As New SqlCommand("AddUserData", connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.Add("@password", SqlDbType.VarChar)
command.Parameters("@password").Value = password
command.Parameters.Add("@login", SqlDbType.VarChar)
command.Parameters("@login").Value = login
command.Parameters.Add("@fullName", SqlDbType.VarChar)
command.Parameters("@fullName").Value = fullName
command.Parameters.Add("@roleID", SqlDbType.Int)
command.Parameters("@roleID").Value = RoleID
command.Parameters.Add("@statusID", SqlDbType.Int)
command.Parameters("@statusID").Value = StatusID
' Open the connection
Try
connection.Open()
command.ExecuteNonQuery()
Finally
connection.Close()
End Try
End Function
now I'm trying to get ahold of the return value from the stored procedure so I can output a message to the user in a label control.
e.g the soted procedure checks to see if a user already exists if it does it returns 55555. how can I get ahold of this 55555 and place it in a variable in the function so I can then send it to another error function to display the approperate lable message ??
thanks all
View 3 Replies
View Related
Mar 17, 2015
How can I find calls which do not exist in stored procedures and functions?We have many stored procedures, sometimes a stored procedure or function which is called does not exist. Is there a query/script or something that I can identify which stored procedures do not 'work' and which procedure/ function they are calling?I am searching for stored procedures and functions which are still called, but do not exist in the current database.
View 7 Replies
View Related
Jun 29, 2004
I would like to capture any errors thrown by linked server in my stored procedure, How do I do this? eg: Select statement in sp to remote server fails if login credentials were changed for some reason on remote server. @@error is not able to capture this error and stored procedure is terminated when this type of error occurs.
View 1 Replies
View Related
Sep 16, 2015
We have a required to run multiple procedures in Single Go . And Error Occurred in any Procedure the it will rollback all the changes( Either all Proc run or None)
DECLARE @StartTime DATETIME=getdate(), @EndTime DATETIME=getdate()-1 , @Message VARCHAR(400)
BEGIN TRY
SET XACT_ABORT ON
BEGIN TRANSACTION
EXEC PROC1 @StartTime,@EndTime,@Message OUTPUT --[ Error Handling done here]
EXEC PROC2 @StartTime,@EndTime,@Message OUTPUT --[ Error Handling done here]
[Code] ....
Problem Statement is its not capturing the Error Message from Either Proc1 or Proc 2., its Capturing the Flat Message (The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction). How do i capture the Error Occurred in Proc 1 or Proc 2 into Log Tables.
View 7 Replies
View Related
Jul 20, 2005
Hi All,I want to catch the next MSSQL error in my SQL code with following continuecalculationsServer: Msg 17, Level 16, State 1, Line 1SQL Server does not exist or access denied.If REMOTE_SERVER_1 is inaccessible (as in (a) below) the executing of SQLwill not continue with (b) - I need the code in (b) to run despite whetherthe previous exec was successful or not - Any ideas?begin transaction(a) exec REMOTE_SERVER_1...bankinsert '1' , '1' , 1 , 0 , 0(b) print @@errorcommit transactionwhere REMOTE_SERVER_1 is link to server created byEXEC sp_addlinkedserver @server = 'REMOTE_SERVER_1', @srvproduct = '',@provider = 'SQLOLEDB', @datasrc = 'MYCOMP1', @catalog = 'mirror2'EXEC sp_addlinkedsrvlogin @rmtsrvname = 'REMOTE_SERVER_1', .....Exec sp_serveroption 'REMOTE_SERVER_1', 'data access', 'true'Exec sp_serveroption 'REMOTE_SERVER_1', 'rpc', 'true'Exec sp_serveroption 'REMOTE_SERVER_1', 'rpc out', 'true'Exec sp_serveroption 'REMOTE_SERVER_1', 'collation compatible', 'true'Any help will be greatly appreciated
View 1 Replies
View Related
May 22, 2008
I've followed the steps in http://www.sqlteam.com/article/debugging-stored-procedures-in-visual-studio-2005 & in the MSDN for configuring and setting up debugging SQL 2005 stored procedures in VS 2008 (seems to be the same as in VS 2005). Everything works fine until I Step Into the Stored Procedure. Everything says that a yellow arrow will appear on the left and I can start going line by line. I never get the yellow arrow.
If I set a breakpoint, it is automatically disabled. The pop-up warning says, "The breakpoint will not currently be hit. Unable to bind SQL breakpoint at this time. Object containing the breakpoint not loaded." I can't find anything about this message or problem on Microsoft's site or on the web. Any assistance is appreciated.
P.S.
I'm running VS 2008 Professional Edition Version 9.0.2.1022.8 RTM
View 7 Replies
View Related
Dec 19, 2003
I have an application where I am bcping a file into a holder table and then looping through each of the rows in that table to add it into the main table for the app. If the data is improperly formatted (ie someone accidently enters 39.Y6 instead of 39.66), we still want to keep it in the system, so we can update the bad fields manually and then import it into the system and keep going through the loop so that if there are 50 rows to import and only one of them is bad, the other 49 will still get imported fine.
I am putting each field from the holder table into a variable and passing them into an existing stored procedure that updates the main table. I had originally checked each one of those variables that had to be numeric or a date to make sure that it was correct before passing them into the procedure but there are about 30 fields so this made the application run unacceptably slow. I then just checked the @@Error value after passing them into the stored procedure (tried after the sp and after the INSERT statement inside the sp) to get that this row didn't insert correctly and move onto the next one. The problem is that the "Error converting data type varchar to numeric" doesn't seem to be handled by the error handling and just bombs the whole thing, so none of the subsequent rows or processing is done.
Is there any way to handle this error and continue the processing without the whole stored procedure crashing? The data entry is being outsourced to India (grrr...), so I don't have any control over checking the data when they enter it and have to do it from within my application on the database side.
View 1 Replies
View Related
Jul 8, 2005
Hi, I'm doing some fairly basic updates with stored procedures. 99% of them affect one row. I've jsut discovered that I can't get the value of @@rowcount and @@error to return as output parameters (if I check one, the other one gets reset!). My theory is then to return the rowcount and if it's not = 1, then I know I've had a problem. If I begin a transaction in vb.net and call each proc in the required order and check each step that rowcount = 1, is this a reliable method of ensuring no errors have occurred?Thanks.
View 2 Replies
View Related
Jan 16, 2003
I have a stored proc that loops through records using a cursor. If during the loop an error occurs i need to trap the error and write it to a log file.
Error handling needs to be placed in the update and insert sections and the error that occurs needs to get recorded along current row from the cursor.
Here is the code:
declare
@tier_id int,
@tier_desctext varchar(50),
@tier_shortdesc varchar(50),
@long_name varchar(50),
@short_name varchar(50),
@rec_count int
--Cursor for UES data
DECLARE cr_ues_tier INSENSITIVE CURSOR
FOR SELECT DISTINCT tier_id, tier_desctext, tier_shortdesc
FROM "dbsourcedayoldprod".ues.dbo.Tiers
OPEN cr_ues_tier
--Select cursor values into local variables
FETCH NEXT FROM cr_ues_tier INTO @tier_id, @tier_desctext, @tier_shortdesc
WHILE (@@FETCH_STATUS <> -1)
BEGIN
--Set Data Mart variables
SELECT @long_name = long_name, @short_name = short_name
FROM uesrpt..coverage_level
WHERE ues_tier_id = @tier_id
--Set the record counter
SET @rec_count = (select ues_tier_id from uesrpt..coverage_level where ues_tier_id = @tier_id)
--Are there exsisting records if so go to the update section
IF @rec_count <> 0
--Update Data Mart values if they have changed
BEGIN
IF @long_name <> @tier_desctext
OR (@long_name IS NULL AND @tier_desctext IS NOT NULL)
OR (@long_name IS NOT NULL AND @tier_desctext IS NULL)
OR @short_name <> @tier_shortdesc
OR (@short_name IS NULL AND @tier_shortdesc IS NOT NULL)
OR (@short_name IS NOT NULL AND @tier_shortdesc IS NULL)
UPDATE uesrpt..coverage_level
SET long_name = @tier_desctext,
short_name = @tier_shortdesc
WHERE ues_tier_id = @tier_id
END
--Rows don't exsist in the Data Mart - Insert new rows
ELSE
INSERT INTO uesrpt..coverage_level (ues_tier_id, long_name, short_name)
SELECT @tier_id, @tier_desctext, @tier_shortdesc
--Get next row from UES cursor
FETCH NEXT FROM cr_ues_tier INTO @tier_id, @tier_desctext, @tier_shortdesc
END
CLOSE cr_ues_tier
DEALLOCATE cr_ues_tier
GO
Any help is appreciated.
Thanks.
View 1 Replies
View Related
Mar 12, 2008
Hi all,
I have a huge stored procedure. part of the query is, the cursor is open and it consist of the implementation for subquery, I want to do an implementation if this subquery return more than one value, catch the error, but continue the cursor operation.
my SQL procedure part looks like:
---code to open the cursor here
WHILE @@FETCH_STATUS=0
BEGIN
SELECT @attachmentCount=count(metaDataID)
FROM View_1
WHERE parentMetaDataID='' + ( SELECT metaDataID
FROM View_1
WHERE metaDataStorageID = @metaStorageID AND parentMetaDataID='0') + '' AND
metaDataContentTypeID=@metaDataContentTypeID
--error handling
DECLARE @err int
SELECT @err = @@error
IF @err <> 0
BEGIN
FETCH NEXT FROM CursorDataStorageID INTO @metaStorageID
CONTINUE
END
FETCH NEXT FROM CursorDataStorageID INTO @metaStorageID
END
-----------------
when I execute this query in SQL management studio, it does return me the no of rows with the msg:
Msg 512, Level 16, State 1, Procedure sp_AdvanceSearchHugeExecution, Line 522
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
But when the stored procedure is called from the within the code ASP.Net, to fill the dataset, I get an exception.
my C# code is simple to fill the dataset using data adapter in try catch block.
Can anyone please suggest how will I able to fill dataset successfully overcoming this mesg?
Thanks a lot.
View 2 Replies
View Related
Aug 25, 2005
OK, i'm trying to do some error checking on stored procedures and amfollowing the advise in Erland Sommarskog's 'Implementing ErrorHandling with Stored Procedures' document.Can anybody help with my stored procedures and why it keeps erroring atthe '-- Create new Address Detail stage'? The errorCode value that isbeing return in my web app is 0, so i'm not even sure why it's evenraising the error!!Rather than executing the INSERT INTO AddressDetail in myCreateSupplier procedure and checking for errors, i'd like to be ableexecute a CreateAddressDetail SP, so that i can reuse it throughout myweb app.New suppliers must have a contact address associated with it, so ifthere's an error creating the suppliers address, i need myCreateSupplier stored procedure to ROLLBACK and not create the newsupplier. That's why i'm not doing two separate calls to the proceduresfrom my app code.Any suggestions are most appreciated.Many thanksDan Williams.CREATE PROCEDURE CreateSupplier@supplierName varchar(50),@userId bigint,@address varchar(50),@town varchar(50),@county varchar(50),@postCode varchar(15),@contactName varchar(50)ASBEGINDECLARE @newSupplierId as bigintDECLARE @newAddressDetailId as bigintDECLARE @errorCode as bigintSET NOCOUNT ONBEGIN TRANINSERT INTO Supplier(supplierName, accOpenedBy, accOpenedDate)VALUES (@supplierName, @userId, getDate())SET @newSupplierId = SCOPE_IDENTITY()-- Check for an error creating new supplierSELECT @errorCode = @@ERRORIF (@errorCode <> 0) BEGIN ROLLBACK TRAN RAISERROR ('Error creatingsupplier',16,1) RETURN @errorCode END-- Create new Address DetailEXEC @errorCode = CreateAddressDetail @address, @town, @county,@postCode, @contactName, @newAddressDetailId OUTPUTSELECT @errorCode = coalesce(nullif(@errorCode, 0), @@error)if @errorCode <> 0 BEGIN ROLLBACK TRAN RAISERROR ('Error creatingaddress. ErrorCode = %d',16, @errorCode) RETURN @errorCode ENDCOMMIT TRANSET NOCOUNT OFFRETURN @newSupplierIdENDGOCREATE PROCEDURE CreateAddressDetail@address varchar(50),@town varchar(50),@county varchar(50),@postCode varchar(15),@contactName varchar(50),@newAddressDetailId bigint OUTPUTASBEGIN-- Create new AddressDetailDECLARE @errorCode as bigintSET NOCOUNT ONBEGIN TRANINSERT INTO AddressDetail(address, town, county, postCode, contactName)VALUES (@address, @town, @county, @postCode, @contactName)SET @newAddressDetailId = SCOPE_IDENTITY()-- Check for an error creating new addressSELECT @errorCode = @@ERRORIF (@errorCode <> 0)BEGINRAISERROR ('Error creating new address detail',16,1)ROLLBACK TRANENDELSECOMMIT TRANSET NOCOUNT OFFRETURN @newAddressDetailIdENDGO
View 9 Replies
View Related
Jul 20, 2005
Hi all,I have a sproc that uses OpenRowset to an Oracle db. If OpenRowseterrors, it terminates the procedure. I need it to continueprocessing. Is there any workaround for this?ThanksPachydermitis
View 1 Replies
View Related
Apr 2, 2002
I am a little confused about something and I am hoping that someone out there has some insight.
Within a stored procedure, I have error handling code just after an INSERT statement. the error handling code basically checks @@ERROR, and if non-zero, logs a message to the NT Event Log. One of the things I want to be able to handle is if the transaction log on the database is full, and the INSERT fails for this reason. However, it appears that for this particular situation (and others I've seen in the past), the stored procedure aborts at the INSERT statement. Never makes it to the error handling code. Is there any way to control this behaviour?
I really need to put in place a failure scenario, if the insert fails, but i can't do that if the stored proc. just aborts on certain types of insert failures.
View 1 Replies
View Related
Jun 4, 2004
I have a Stored Proc that is called by a SQL Job in SQL Server 2000. This stored proc deadlocks once every couple of days. I'm looking into using the @@error and try to doing a waitfor .5 sec and try the transaction again. While looking around google I've come across a few articles stating that a deadlock inside a Stored Proc will stop all execution of the stored proc so I will not be able doing any error handling. Is this true? Does anyone have any experience that could help me out?
I know the best solution would be to resolve why I get a deadlock. We are currently looking into that but until we can resolve those issues I would like to get some type of error handling in place if possible.
Thank you,
DMW
View 8 Replies
View Related
Jan 3, 2008
I am stumped on the error reporting with sql server. I was told ineed to return @SQLCode(code showing if successful or not) and@ErrMsg(and the message returned). I am clueless on this.I wrote this procedure:
Code: ( text )
View 4 Replies
View Related
Jul 20, 2005
Hi,I a stored procedure that inserts a record into a table asbelow.The insert works OK, but if the insert violates a uniqueindewx constraint on one of the columns, the proc terminatesimmediately, and does NOT execute the 'if @@ERROR <> 0'statement.Am I doing something wrong, or do I need to set an attributesomewhere?tia,Billbegin traninsert into Users(UserName, UserPWD, Lname, Fname, UserDesc)values (@userName, @userPWD, @lname, @fname, @userDesc)if @@ERROR <> 0beginrollback transet @returnCode = -2set @errMsg = 'SQL error '+ convert(varchar(6), @@ERROR)+ ' occurred adding user '+ @userNameend
View 1 Replies
View Related
Sep 24, 2007
Can anyone let me know the prefered method for handling stored procedure errors. I usually trap the error in the stored proc and then return a value using an output parameter
e.g stored proc
if @@error <> 0 beginset @returnValue = -1returnend
c#com.Parameters.Add("@returnValue", SqlDbType.Int).Direction = ParameterDirection.Output;con.Open();com.ExecuteNonQuery();
int result = (int)com.Parameters[0].Value;
if (result == -1){//throw exception}else{//do whatever}
View 2 Replies
View Related
Jul 23, 2005
I want to know the differences between SQL Server 2000 storedprocedures and oracle stored procedures? Do they have differentsyntax? The concept should be the same that the stored proceduresexecute in the database server with better performance?Please advise good references for Oracle stored procedures also.thanks!!
View 11 Replies
View Related
Jan 29, 2015
I have some code that I need to run every quarter. I have many that are similar to this one so I wanted to input two parameters rather than searching and replacing the values. I have another stored procedure that's executed from this one that I will also parameter-ize. The problem I'm having is in embedding a parameter in the name of the called procedure (exec statement at the end of the code). I tried it as I'm showing and it errored. I tried googling but I couldn't find anything related to this. Maybe I just don't have the right keywords. what is the syntax?
CREATE PROCEDURE [dbo].[runDMQ3_2014LDLComplete]
@QQ_YYYY char(7),
@YYYYQQ char(8)
AS
begin
SET NOCOUNT ON;
select [provider group],provider, NPI, [01-Total Patients with DM], [02-Total DM Patients with LDL],
[Code] ....
View 9 Replies
View Related
Nov 6, 2005
I'm involved in the developement/maintanance of a database that has a lot of stored procedures. The procedures are constantly developed and it would be good to have some kind of version handling connected to them.
Is there any way to achive this?
/Lars
View 1 Replies
View Related
Apr 26, 2000
How to capture errors occured in stored procedures in case SQL SERVER7?
View 1 Replies
View Related
Apr 4, 2006
Hi I think by virtue of not being able to find reference to this I have my answer however.... You trap an error, check it and know that you are happy with it - it isn't an issue. Is it possible to prevent that specific error (number, message - the lot) being passed to the client so developers don't need to handle the error a second time? Ta db chucks :D
View 9 Replies
View Related
Jun 19, 2015
I have a periodic backup task, and when I need a development copy on which to test code, I restore my most recent backup to a different name, switch the ODBC link to that name on my development machine and have a current copy of the database to play with.
I've been doing this for years, and it works great. Just now I did it, and suddenly my development machine is unable to run any stored procedures that have the 'Execute as owner' clause in their definition. I'm using domain accounts, my personal account is the owner of the database, and everything works on the production copy, which is in the same instance on the same machine.
The test copy is identical to the production copy, which continues to work fine - it was just created using by restoring the backup of the production copy, but I can't run anything with this clause. As soon as I delete the 'Execute as owner' line, the procedure is suddenly available. If I put it back, I'm locked out again.
The error message is: The server principal “sa” is not able to access the database “WhateverDB” under the current security context
View 5 Replies
View Related
Jul 27, 2015
who i can to list the content of all store procedures and funtions in text file ?
View 3 Replies
View Related
Apr 28, 2008
Hi all,
In my code, I will call a stored procedure which is stored on the SQL server. However, I got errors on the stored procedure (The multi-part identifier "Datetime.Today" could not be bound.). Anyone know how to fix it. Thanks in advance.
ALTER PROCEDURE [dbo].[spr_getScheduleJob]( @ToMobNum varchar(16), @OADC varchar(11), @MsgScheduleTime smalldatetime, @MsgTxt varchar(160), @CompUserName varchar(20) )
asset nocount on
Declare @TodayJobs as smalldatetimeSet @TodayJobs = Datetime.Todayselect * from Bulk_ScheduledOutgoing where @TodayJobs <= @MsgScheduleTime
View 3 Replies
View Related
Sep 22, 1999
I was wondering if anyone knows how to suppress error messages that get returned from a stored procedure. For example, in a stored procedure I have a convert statement that takes some dates and substrings them together into a new date format:
select convert(datetime(substring(col1,1,2)+ '/' +.......etc.
Some of the data I am working with is not guaranteed to be good. For example, sometimes the users had entered 2/2/97 - which is invalid - no leap year in 1997. So, the convert to datetime fails.
The typical error message about the convert pops up on the screen. Can I shut that off.....and still catch @@error <> 0....?
Thanks!
Dean
View 1 Replies
View Related