Welcome to Experts Exchange

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

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

Begin Transaction Commit Transaction for Loop

Posted on 2006-11-04
Last Modified: 2008-01-09

I have an asp 'survey' application that sends data to a SQL SERVER 2005 Database.  The problem is that I send the results to the database in a loop with an Insert for each question (max 20 questions) so how do I ensure data integrity when each transaction is autonomous.  The asp code looks something like this:


Get the data (QuestionID and Result) --- result is integer from 0 -5

Do While QuestionCount < NumQuestions
Get Response Details
Insert To SQL Stored Procedure(QuestionID, Result, CourseID, Section, Comments, Instructor...)

I have a Begin Transaction and Commit Transaction in the stored procedure but if there is a problem, only the current record will not be committed - the previous records have been committed and I am left with an incomplete survey.  A problem could and did happen, even though I code for 'SQL' oddities in the comments.

I have thought about holding all 20 of the question results and comments in some sort of an array and passing an array to SQL but that seems very difficult and overly complex.  HELP.

Vince Stack
Question by:vstack
  • 6
  • 4
  • 4
  • +2
LVL 35

Accepted Solution

Raynard7 earned 500 total points
ID: 17875352

the other option is to have your stored procedure return the identity for each row that you are inserting.  You could then store that in an array - and if one failed you could then go through and delete each identity.  This way you would ensure that if any failed then all your questions could be removed - leaving you in the same situation you had before inserting the data.

Expert Comment

ID: 17875368
MS SQL Server supports nested transactions. so  before the loop do BEGIN TRAN. if any of the iterations through the loop has failed, after the loop do ROLLBACK TRAN, otherwise, after the loop do COMMIT TRAN.


Author Comment

ID: 17875369
That was fast and it sounds like a reasonable solution; however, how do I return the scope identity and how do I not have my application blow up when a problem occurs.  For example, how do I test for an error and simply send a message back to .asp from the stored procedure that there was a problem?

Here is my stored procedure:

ALTER PROCEDURE [dbo].[qInsertDataToTblResults]
@QuestionID int,
@InstructorID int,
@Result int,
@ProgramID int,
@Comments varchar(max),
@CourseID nvarchar(50),
@SectionID int,
@LongAnswer int,  */ this is 0 or 1 indicating a question that requires a long answer (comment)
@Facility int,  */ this is 0 or 1 indicating a question about campus facilites and not about a particular course
@CourseSpecific int,
@SurveyID int,
@InstructorSpecific int,
@surveydate nvarchar(50) */ this is simply a string indicating the semester and year (FALL2006)
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.

    -- Insert statements for procedure here
Begin Transaction
Insert Into tblSurveyResults (QuestionID, InstructorID, Result, ProgramID, Comments, CourseID, SectionID, LongAnswer, Facility, CourseSpecific, SurveyID, InstructorSpecific, SurveyDate) Values (@QuestionID, @InstructorID, @Result, @ProgramID, @Comments, @CourseID, @SectionID, @LongAnswer, @Facility, @CourseSpecific, @SurveyID, @InstructorSpecific, @SurveyDate)
Commit Transaction
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.


Expert Comment

ID: 17875373
for further info, please look at :


Author Comment

ID: 17875374
MS SQL Server supports nested transactions?  See this is where my competency ends.   Do you mean that I could put a Begin Transaction before my loop and a Commit Transaction at the end of the loop in .asp?
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 17875387
The best option in this situation is to build an xml at the front end and pass it to a modified version of the above procedure.This needs only one transaction ..
LVL 35

Expert Comment

ID: 17875392
aneeshattingal's option sounds the cleanest of all, then you only need to process the results once - send them to the database once - then have the stored procedure that accepts the xml just return if it was successful or not.

Expert Comment

ID: 17875399
generally, yes.

i have no enough experience with asp. i believe you can do it in your asp code. however, even in a desktop application i would pass the question Id's to another stored procedure which contains a similar loop that call another stored procedure (the one you mentioned and posted).


Author Comment

ID: 17875414
XML - while that sounds great, I have no experience with it.
LVL 35

Expert Comment

ID: 17875424

In terms of getting the XML to work the below questions have expamles of how a stored procedure can read the xml and some loose information on how to create it.

http:Q_21602148.html "Passing multiple values to a WHERE IN statement using a parameter"
http:Q_21583322.html "Inserting multiple rows efficiently"
http:Q_21536499.html "Multiple records added to TABLE variable (stored procedure)"
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 17875427
> XML - while that sounds great, I have no experience with it.
The XML building process may be bit hard, in sql it is simple. read Boos online

Author Comment

ID: 17875433
Thanks.  I'll read up on it.  Sounds like something I should know.
LVL 75

Expert Comment

by:Anthony Perkins
ID: 17876629
Here is another example using OPENXML:

Or better still post some sample insert statements, your table structure and we can provide a full solution.

Author Comment

ID: 17878689

Here is the insert I use and the loop.  

Do While QCount < Cint(NumQuestions)
correspondComment = QuestionCountArray(QCount)
CommentCount = Cstr(correspondComment)
theComment = theComment + CommentCount
theComment = Request.Form(theComment)
theComment = SQLFixup(theComment)
correspondResult = QuestionCountArray(QCount)
correspondResult = cstr(correspondResult)
correspondResult = Request.Form(QPrefix + correspondResult)
if correspondResult = "" then
correspondResult = 4
end if
correspondResult = correspondResult - 0
QuestionID = QuestionCountArray(QCount)
QuestionID = QuestionID - 0
if QuestionID > 0 then
Set objRS_instructorspecific = Server.CreateObject("ADODB.Recordset")
'this tells me whether or not the question is specific to an instructor
'like does instructor show up on time?
'important for calculating instructor results
'I suppose I could somehow pass this from the questions page
objRS_instructorspecific.Open "Exec qGetInstructorSpecificQuestions " & QuestionID, objConn
response.write "This survey has been completed OR you have attempted to submit without using the Submit Survey button."
end if
instructorspecific = objRS_instructorspecific("InstructorSpecific")      
instructorspecific = instructorspecific - 0
Set objRS_instructorspecific = Nothing
'new insert into results
CourseSpecific = 1
'indicates a question regarding college facilities like lbrary, cafeteria, etc.  In this case always 0
Facility = 0
'I process all short answer (radio button responses here so I know that all Q's are short answer types
LongAnswer = 0
'insert statement
objConn.Execute("qInsertDataToTblResults " & QuestionID & ", " & InstructorID & "," & correspondResult & ", " & ProgramID & ", '" & theComment & "', '" & CourseID & "', " & SectionID & ", " & LongAnswer & ", " & Facility & ", " & CourseSpecific & ", " & SurveyID & "," & instructorspecific & ", '" & surveydate & "'")
theComment = "Comment"
QCount = QCount + 1

The info is gathered and sent to a results table
Here is the results table structure

CREATE TABLE [dbo].[tblSurveyResults](
      [QuestionID] [int] NOT NULL CONSTRAINT [DF__tblSurvey__Quest__7C8480AE]  DEFAULT ((0)),
      [Result] [float] NOT NULL CONSTRAINT [DF__tblSurvey__Resul__7D78A4E7]  DEFAULT ((4)),
      [InstructorID] [int] NULL CONSTRAINT [DF__tblSurvey__Instr__7E6CC920]  DEFAULT ((0)),
      [CourseID] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
      [Comments] [varchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NULL CONSTRAINT [DF_tblSurveyResults_Comments]  DEFAULT (NULL),
      [ProgramID] [int] NULL CONSTRAINT [DF__tblSurvey__Progr__7F60ED59]  DEFAULT ((0)),
      [SectionID] [int] NULL CONSTRAINT [DF__tblSurvey__Secti__00551192]  DEFAULT ((1)),
      [LongAnswer] [bit] NULL CONSTRAINT [DF__tblSurvey__LongA__014935CB]  DEFAULT ((0)),
      [CourseSpecific] [bit] NULL CONSTRAINT [DF__tblSurvey__Cours__023D5A04]  DEFAULT ((0)),
      [Facility] [bit] NULL CONSTRAINT [DF__tblSurvey__Facil__03317E3D]  DEFAULT ((0)),
      [SurveyID] [int] NOT NULL CONSTRAINT [DF__tblSurvey__Surve__0425A276]  DEFAULT ((0)),
      [InstructorSpecific] [bit] NULL CONSTRAINT [DF__tblSurvey__Instr__0519C6AF]  DEFAULT ((0)),
      [SurveyDate] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL

LVL 75

Expert Comment

by:Anthony Perkins
ID: 17878814
If you want to pursue using Xml, than you should understand that there are two stages to this.
1.  Make sure that the Stored Procedure functions as you would like.
2.  Make sure the ASP builds the Xml documents correctly and calls the Stored procedure appropriately.

Here in this Topic Area we can address step 1 and give you general pointers for step 2.

So first see if you can "post some sample insert statements" as they stand now (three or four would be adequate), so that we can make sure you understand how the stored procedure works.  I can certainly make up some values for the parameters, but it may not be very meaningful.
LVL 75

Expert Comment

by:Anthony Perkins
ID: 17878889
To give you an idea, the stored procedure could look like this (using xml attributes for the values):

ALTER PROCEDURE dbo.qInsertXmlDataToTblResults
      @Questions varchar(max)

Declare @iDoc int


EXEC sp_xml_preparedocument @iDoc OUTPUT, @Questions

Insert      tblSurveyResults (
       QuestionID, InstructorID, Result, ProgramID, Comments, CourseID, SectionID, LongAnswer,
       Facility, CourseSpecific, SurveyID, InstructorSpecific, SurveyDate)
Select      QuestionID, InstructorID, Result, ProgramID, Comments, CourseID, SectionID,
                  LongAnswer, Facility, CourseSpecific, SurveyID, InstructorSpecific, SurveyDate
From      OPENXML (@iDoc, 'Questions/Question', 1) WITH (
             QuestionID integer '@questionID',
            InstructorID integer '@instructorID',
            Result int '@result',
            ProgramID integer '@programID',
            Comments varchar(max) '@comments',
            CourseID nvarchar(50) '@courseID',
            SectionID int '@sectionID',
            LongAnswer int '@longAnswer',
            Facility int '@facility',
            CourseSpecific int '@courseSpecific',
            SurveyID int '@surveyID',
            InstructorSpecific int '@instructorSpecific',
            SurveyDate nvarchar(50) '@surveyDate')

EXEC sp_xml_removedocument @iDoc
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 17912320
hope you didn't try the XML part


Author Comment

ID: 17912605
I tried it but I could not get anywhere with it.  I still appreciate the suggestion.
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 17912638
>I tried it but I could not get anywhere with it.
I think you should post here to see where you went wrong ?
LVL 75

Expert Comment

by:Anthony Perkins
ID: 17919412
>>I tried it but I could not get anywhere with it. <<
Unfortunately this is the MS SQL Server Topic Area not the ESP TA, so it is difficult to help without feedback.

Featured Post

The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
MIcrosoft SQL 2014 Database Copy Question 16 51
t-sql need help on t-sql 10 25
Download ms sql express. 2 23
SQL Log size 3 16
When you hear the word proxy, you may become apprehensive. This article will help you to understand Proxy and when it is useful. Let's talk Proxy for SQL Server. (Not in terms of Internet access.) Typically, you'll run into this type of problem w…
Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

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

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

Join & Ask a Question