Concurrency Handling In Stored Procedures
Jul 23, 2005
I have a requirement that requires detection of rows deleted/updated by
other processes. My business objects call stored procedures to create,
read, update, delete data in a SQL Server 2000 data store. I've done
a fair amount of research on concurrency handling in newsgroups and
other resources. Below is what I've come up as a standard for
handling concurrency thru stored procedures. I am sharing with everyone
so I can get some comments (pro/con) regarding this approach and see if
anyone can find any holes for this solution.
Below is the DDL, DML and a Stored Proc demonstrating the approach. I
am using a rowversion column for concurrency checking. Another approach
that is less intrusive (doesn't require having a rowversion column in
all tables) is using checksum. I may eventually use checksum but the
process flow should be almost identical. Looking forward to anyone's
comments.
Thx, BZ
--xxxxxxxxxxxxxxxxxxxxxxxxxxx--
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'U' AND name =
'ApplicationUsers')
BEGIN
PRINT 'Dropping Table ApplicationUsers'
DROP Table dbo.ApplicationUsers
END
GO
PRINT 'Creating Table ApplicationUsers'
GO
CREATE 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
)
GO
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name =
'UpdateUser')
BEGIN
PRINT 'Dropping Procedure UpdateUser'
DROP Procedure dbo.UpdateUser
END
GO
PRINT 'Creating Procedure UpdateUser'
GO
Create Procedure dbo.UpdateUser
@loginName Varchar (20),
@loginPassword Varchar (50),
@loginAttempts Int,
@emailAddress Varchar(25),
@dataVersion Rowversion Output
As
/************************************************** ****************************
** 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 concurrency
control.
**
** 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 On
Declare
@err Int,
@rowCount Int,
@tranCount Int
--Transaction Handling
Select @tranCount = @@TRANCOUNT
If (@tranCount=0)
Begin Tran LocalTran
Else
Save Tran LocalTran
Update
dbo.ApplicationUsers
Set
LoginPassword = @loginPassword,
LoginAttempts = @loginAttempts,
EmailAddress = @emailAddress
Where
LoginName = @loginName
And
DataVersion = @dataVersion
--Check for errors and rowCount (Should have updated 1 row)
Select @err = @@ERROR, @rowCount = @@ROWCOUNT
If (@err != 0) GOTO ErrHandler
If (@rowCount != 1) GOTO ConcurrencyHandler
--Set dataversion output parameter
Select
@dataVersion = DataVersion
From
dbo.ApplicationUsers
Where
LoginName = @loginName
/*
If we got this far then there were no errors
If this proc started transaction then commit it,
otherwise return and let caller handle transaction
*/
If (@TranCount = 0)
Commit Tran LocalTran
Return 0
/*
Rollback local transaction if an error was encountered.
Return code is used to communicate error number.
*/
--Handle Concurrency Errors
ConcurrencyHandler:
Rollback Tran LocalTran
If Exists (Select * From dbo.ApplicationUsers where LoginName =
@loginName)
Return 66661 --Row version doesn't match provided version
Else
Return 66666 --Row not found
--Handle Other Errors
ErrHandler:
Rollback Tran LocalTran
Return @err --Return Err Number
GO
PRINT 'Inserting Test Data...'
--Add Test Data
Insert 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 Version
select @rowvrsn = DataVersion from dbo.ApplicationUsers where LoginName
= 'blackmamba'
Exec @retVal = dbo.UpdateUser @loginName = 'blackmamba', @loginPassword
= 'UpdatedPwd', @loginAttempts = 0, @emailAddress = 'bm@DIVAS.com',
@dataVersion = @rowvrsn output
Print @retVal --Should be 0 for success
GO
/*
Call UpdateUser Stored Proc with out of date rowversion (simulate
update by other process)
*/
Declare @retVal int, @rowvrsn rowversion
--Get Current Row Version
select @rowvrsn = DataVersion from dbo.ApplicationUsers where LoginName
= 'blackmamba'
--Simulate update by other process
Update dbo.ApplicationUsers Set LoginPassword = LoginPassword where
LoginName = 'blackmamba'
--Update User with out of date Rowversion
Exec @retVal = dbo.UpdateUser @loginName = 'blackmamba', @loginPassword
= 'UpdatedPwdVersion2', @loginAttempts = 0, @emailAddress =
'bm@DIVAS.com', @dataVersion = @rowvrsn output
Print @retVal --Should be 66661 for rowversion mismatch
GO
/*
Call UpdateUser Stored Proc with out of date rowversion (simulate
delete by other process)
*/
Declare @retVal int, @rowvrsn rowversion
--Get Current Row Version
select @rowvrsn = DataVersion from dbo.ApplicationUsers where LoginName
= 'blackmamba'
--Simulate delete by other process
Delete From dbo.ApplicationUsers where LoginName = 'blackmamba'
--Update User with out of date Rowversion
Exec @retVal = dbo.UpdateUser @loginName = 'blackmamba', @loginPassword
= 'UpdatedPwdVersion2', @loginAttempts = 0, @emailAddress =
'bm@DIVAS.com', @dataVersion = @rowvrsn output
Print @retVal --Should be 66666 for row deleted by other process
View 2 Replies
ADVERTISEMENT
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
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
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
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
Apr 1, 2005
I'm using Java to connect to a SQL Server 2000 database. I connect using the Driver Manager with Sun's odbc driver ( sun.jdbc.odbc.JdbcOdbcDriver ) or I can use the jdbc driver provided by Microsoft (com.microsoft.jdbc.sqlserver.SQLServerDriver)
The Java application makes 1 Connection.
Within the database there exists a stored procedure that updates 2 Tables. The tables have a fixed number of rows that get updated continuously by calls to this stored procedure.
The Java application has a thread pool of 15 threads that create 15 CallableStatements (1 per thread) using the same instance of the Connection object.
According the the Microsoft JDBC driver docs, 1 Connection with multiple calls to the Callable statements is how it's supposed to be done. The following is an excerpt from Microsoft's "SQL Server 2000 Driver for JDBC User’s Guide and Reference" (page 86) regarding Connection Managment:
Managing Connections
Connection management is important to application performance. Optimize your application by connecting once and using multiple statement objects, instead of performing multiple connections. Avoid connecting to a data source after establishing an initial connection.
This is precisely what I'm doing, but I do not know if the the stored procedures are being run concurrently, the documentation does not tell me.
So my question: What is happening inside SQL Server 2000?
View 2 Replies
View Related
Dec 11, 2007
I am working on application developed in ASP.NET 2.0 that uses lots of stored procedures from the SQL Server 2000 backend database.When the app is under load you occasionally see incorrect data returned to the page after running stored procedures.
All the stored procedures have been tested and appear to be fine. it's as if under load the returned data from the stored procedures is getting 'mixed' with another concurrent session.
Please let me know what could be the reason behind it
View 6 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
Jul 18, 2007
Hi
I've implemented an SQL-CLR stored procedure which makes an HTTP connection using the WebClient class to a server where the processing on the web server takes 10 seconds.
If I fire off a bunch of requests to the stored procedure, e.g. 80 in 1 second I noticed that SQL Server 2005 (Express Edition) only allows 2 concurrent network connections at a time.
I can confirm this by looking at the timing of the results when they come back, basically I get 2 results every 10 seconds and by doing a 'netstat -a' on the web server I notice that there are never more than 2 HTTP connections from the SQL Server at a time.
Is this some sort of sheduling policy in terms of the number of concurrent external network accesses allowed by CLR objects running in SQL Server? Or some side effect of the way the WebClient class blocks in terms of waiting for a network response?
I was expecting all 80 of the requests to block waiting on a network response almost immediately and then for all 80 of them to pretty much complete and return 10-11 seconds later.
[Microsoft.SqlServer.Server.SqlProcedure]
public static int CreditAuthorisation(string Name, decimal Amount)
{
WebClient client = new WebClient();
string result = client.DownloadString("http://someserver/Test.aspx");
return int.Parse(result);
}
Cheers
View 4 Replies
View Related
Sep 30, 2006
Hi,
This Might be a really simple thing, however we have just installed SQL server 2005 on a new server, and are having difficulties with the set up of the Store Procedures. Every time we try to modify an existing stored procedure it attempts to save it as an SQL file, unlike in 2000 where it saved it as part of the database itself.
Thank you in advance for any help on this matter
View 1 Replies
View Related
Nov 6, 2007
Using SQL 2005, SP2. All of a sudden, whenever I create any stored procedures in the master database, they get created as system stored procedures. Doesn't matter what I name them, and what they do.
For example, even this simple little guy:
CREATE PROCEDURE BOB
AS
PRINT 'BOB'
GO
Gets created as a system stored procedure.
Any ideas what would cause that and/or how to fix it?
Thanks,
Jason
View 16 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
Jan 21, 2008
Hi all,
I’m returning two values from a stored procedure, one is a basic string confirming that an email has been sent and the other is the normal value returned from running an INSERT statement. So in my code I’m using the ExecuteNonQuery() method. I’m not sure how to handle both returned values in my code in my data layer. This is what I have:
ExecuteNonQuery(cmd);
return Convert.ToString(cmd.Parameters["@ReturnedValue"].Value).ToLower();
Obviously I’d need to return the value returned by the ExecuteNonQuery method as well, normally I’d simply convert the value to an int and precede this with the return keyword like so:
return (int)ExecuteNonQuery(cmd);
Obviously I can’t do this as I need to return two values, the normal value returned by the ExecuteNonQuery() method and my own output parameter value. Any ideas how I can do both? My current method containing the code further above returns a string but clearly this doesn’t help. I’m guessing that maybe I should return an object array so I can return both values? I haven’t encountered this problem before so I’m just guessing. Please help.
Thanks
View 4 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
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
Apr 29, 2008
How do I search for and print all stored procedure names in a particular database? I can use the following query to search and print out all table names in a database. I just need to figure out how to modify the code below to search for stored procedure names. Can anyone help me out?
SELECT TABLE_SCHEMA + '.' + TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
View 1 Replies
View Related
Jun 13, 2007
Seems like I'm stealing all the threads here, : But I need to learn :) I have a StoredProcedure that needs to return values that other StoredProcedures return.Rather than have my DataAccess layer access the DB multiple times, I would like to call One stored Procedure, and have that stored procedure call the others to get the information I need. I think this way would be more efficient than accessing the DB multiple times. One of my SP is:SELECT I.ItemDetailID, I.ItemDetailStatusID, I.ItemDetailTypeID, I.Archived, I.Expired, I.ExpireDate, I.Deleted, S.Name AS 'StatusName', S.ItemDetailStatusID, S.InProgress as 'StatusInProgress', S.Color AS 'StatusColor',T.[Name] AS 'TypeName', T.Prefix, T.Name AS 'ItemDetailTypeName', T.ItemDetailTypeID FROM [Item].ItemDetails I INNER JOIN Item.ItemDetailStatus S ON I.ItemDetailStatusID = S.ItemDetailStatusID INNER JOIN [Item].ItemDetailTypes T ON I.ItemDetailTypeID = T.ItemDetailTypeID However, I already have StoredProcedures that return the exact same data from the ItemDetailStatus table and ItemDetailTypes table.Would it be better to do it above, and have more code to change when a new column/field is added, or more checks, or do something like:(This is not propper SQL) SELECT I.ItemDetailID, I.ItemDetailStatusID, I.ItemDetailTypeID, I.Archived, I.Expired, I.ExpireDate, I.Deleted, EXEC [Item].ItemDetailStatusInfo I.ItemDetailStatusID, EXEC [Item].ItemDetailTypeInfo I.ItemDetailTypeID FROM [Item].ItemDetails IOr something like that... Any thoughts?
View 3 Replies
View Related
May 13, 2008
Greetings:
I have MSSQL 2005. On earlier versions of MSSQL saving a stored procedure wasn't a confusing action. However, every time I try to save my completed stored procedure (parsed successfully ) I'm prompted to save it as a query on the hard drive.
How do I cause the 'Save' action to add the new stored procedure to my database's list of stored procedures?
Thanks!
View 5 Replies
View Related
Apr 7, 2006
We recently upgraded to SQL Server 2005. We had several stored procedures in the master database and, rather than completely rewriting a lot of code, we just recreated these stored procedures in the new master database.
For some reason, some of these stored procedures are getting stored as "System Stored Procedures" rather than just as "Stored Procedures". Queries to sys.Objects and sys.Procedures shows that these procs are being saved with the is_ms_shipped field set to 1, even though they obviously were not shipped with the product.
I can't update the sys.Objects or sys.Procedures views in 2005.
What effect will this flag (is_ms_shipped = 1) have on my stored procedures?
Can I move these out of "System Stored Procedures" and into "Stored Procedures"?
Thanks!
View 24 Replies
View Related
Apr 23, 2008
Hello friends......How are you ? I want to ask you all that how can I do the following ?
I want to now that how many ways are there to do this ?
How can I call one or more stored procedures into perticular one Stored Proc ? in MS SQL Server 2000/05.
View 1 Replies
View Related
Mar 26, 2008
Hello
I'm start to work with SSIS.
We have a lot (many hundreds) of old (SQL Server2000) procedures on SQL 2005.
Most of the Stored Procedures ends with the following commands:
SET @SQLSTRING = 'SELECT * INTO ' + @OutputTableName + ' FROM #RESULTTABLE'
EXEC @RETVAL = sp_executeSQL @SQLSTRING
How can I use SSIS to move the complete #RESULTTABLE to Excel or to a Flat File? (e.g. as a *.csv -File)
I found a way but I think i'ts only a workaround:
1. Write the #Resulttable to DB (changed Prozedure)
2. create data flow task (ole DB Source - Data Conversion - Excel Destination)
Does anyone know a better way to transfer the #RESULTTABLE to Excel or Flat file?
Thanks for an early Answer
Chaepp
View 9 Replies
View Related
Jun 16, 2007
Hi,
Do you know how to write stored procedures inside another stored procedure in MS SQL.
Create procedure spMyProc inputData varchar(50)
AS
----- some logical
procedure spMyProc inputInsideData varchar(10)
AS
--- some logical
--- go
-------
View 5 Replies
View Related
May 8, 2008
I am writing a set of store procedures (around 30), most of them require the same basic logic to get an ID, I was thinking to add this logic into an stored procedure.
The question is: Would calling an stored procedure from within an stored procedure affect performance? I mean, would it need to create a separate db connection? am I better off copying and pasting the logic into all the store procedures (in terms of performance)?
Thanks in advance
John
View 5 Replies
View Related
Nov 1, 2007
Hi all - I'm trying to optimized my stored procedures to be a bit easier to maintain, and am sure this is possible, not am very unclear on the syntax to doing this correctly. For example, I have a simple stored procedure that takes a string as a parameter, and returns its resolved index that corresponds to a record in my database. ie
exec dbo.DeriveStatusID 'Created'
returns an int value as 1
(performed by "SELECT statusID FROM statusList WHERE statusName= 'Created')
but I also have a second stored procedure that needs to make reference to this procedure first, in order to resolve an id - ie:
exec dbo.AddProduct_Insert 'widget1'
which currently performs:SET @statusID = (SELECT statusID FROM statusList WHERE statusName='Created')INSERT INTO Products (productname, statusID) VALUES (''widget1', @statusID)
I want to simply the insert to perform (in one sproc):
SET @statusID = EXEC deriveStatusID ('Created')INSERT INTO Products (productname, statusID) VALUES (''widget1', @statusID)
This works fine if I call this stored procedure in code first, then pass it to the second stored procedure, but NOT if it is reference in the second stored procedure directly (I end up with an empty value for @statusID in this example).
My actual "Insert" stored procedures are far more complicated, but I am working towards lightening the business logic in my application ( it shouldn't have to pre-vet the data prior to executing a valid insert).
Hopefully this makes some sense - it doesn't seem right to me that this is impossible, and am fairly sure I'm just missing some simple syntax - can anyone assist?
View 1 Replies
View Related