Solved

Begin Transaction Commit Transaction for Loop

Posted on 2006-11-04
20
1,212 Views
Last Modified: 2008-01-09
Hi,

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...)
Loop

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
0
Comment
Question by:vstack
  • 6
  • 4
  • 4
  • +2
20 Comments
 
LVL 35

Accepted Solution

by:
Raynard7 earned 500 total points
ID: 17875352
Hi,

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.
0
 
LVL 5

Expert Comment

by:ewilde
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.

regards,
ewilde.
0
 

Author Comment

by:vstack
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)
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

    -- 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
END
0
 
LVL 5

Expert Comment

by:ewilde
ID: 17875373
for further info, please look at :

http://msdn2.microsoft.com/en-us/library/ms188929.aspx
0
 

Author Comment

by:vstack
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?
0
 
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 ..
:)
0
 
LVL 35

Expert Comment

by:Raynard7
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.
0
 
LVL 5

Expert Comment

by:ewilde
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).

regards,
ewilde.
0
 

Author Comment

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

Expert Comment

by:Raynard7
ID: 17875424
Hi,

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)"
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 17875427
vstack,
> 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
0
 

Author Comment

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

Expert Comment

by:Anthony Perkins
ID: 17876629
Here is another example using OPENXML:
http://www.experts-exchange.com/Databases/Microsoft_SQL_Server/Q_21599595.html

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

Author Comment

by:vstack
ID: 17878689
Wow!

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
else
response.write "This survey has been completed OR you have attempted to submit without using the Submit Survey button."
Session.Abandon
response.end
end if
instructorspecific = objRS_instructorspecific("InstructorSpecific")      
instructorspecific = instructorspecific - 0
objRS_instructorspecific.Close
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
Loop

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
)



0
 
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.
0
 
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)
AS

Declare @iDoc int

SET NOCOUNT ON

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
0
 
LVL 75

Expert Comment

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

:(
0
 

Author Comment

by:vstack
ID: 17912605
I tried it but I could not get anywhere with it.  I still appreciate the suggestion.
0
 
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 ?
0
 
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.
0

Featured Post

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Join & Write a Comment

Suggested Solutions

Introduction SQL Server Integration Services can read XML files, that’s known by every BI developer.  (If you didn’t, don’t worry, I’m aiming this article at newcomers as well.) But how far can you go?  When does the XML Source component become …
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.
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…

708 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now