unable to execute query in ASP - asp-classic

Following is the ASP code that I am working on:
Dim sConnString, connection, sSQL, backgroundColor
sSQL = "SELECT firstName, lastName, email, zip, country, company, industry, revenue, timestamp FROM users"
sConnString=//a connection string
Set connection = Server.CreateObject("ADODB.Connection")
connection.Mode=adModeRead
connection.Open(sConnString)
connection.execute(sSQL)
Response.Write"<table>"
do while not connection.EOF
if(backgroundColor="#f1f1f1")then
backgroundColor="#ffffff"
else
backgroundColor="#f1f1f1"
end if
response.write"<tr backgroundColor="& backgroundColor & "></td>" & connection("firstName") & "</td><td>" & connection("lastName") & "</td><td>" & connection("email") & "</td><td>" & connection("zip") & "</td><td>" & connection("country") & "</td><td>" & connection("company") & "</td><td>" & connection("industry") & "</td><td>" & connection("revenue") & "</td><td>" & connection("timestamp") & "</td></tr>"
connection.MoveNext
Loop
Response.Write"</table>"
connection.Close
Set connection = Nothing
I am getting the following error:
ADODB.Connection error '800a0bb9'
Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another.
/wsu.asp, line 13
Line 13:
do while not connection.EOF
Could you please help me with this?
Updated code:
<html>
<body>
<%
Dim sConnString, connection, sSQL, backgroundColor
sSQL = "SELECT firstName, lastName, email, zip, country, company, industry, revenue, timestamp FROM users"
sConnString="a connection string for MS SQL database;"
Set connection = Server.CreateObject("ADODB.Connection")
Set rs = Server.CreateObject("ADODB.Recordset")
connection.Mode=adModeRead
rs.open sSQL,connection
Response.Write"<table>"
do while not connection.EOF
if(backgroundColor="#f1f1f1")then
backgroundColor="#ffffff"
else
backgroundColor="#f1f1f1"
end if
response.write "<tr backgroundColor="& backgroundColor & "></td>" & connection("firstName") & "</td><td>" & connection("lastName") & "</td><td>" & connection("email") & "</td><td>" & connection("zip") & "</td><td>" & connection("country") & "</td><td>" & connection("company") & "</td><td>" & connection("industry") & "</td><td>" & connection("revenue") & "</td><td>" & connection("timestamp") & "</td></tr>"
connection.MoveNext
Loop
Response.Write"</table>"
connection.Close
Set connection = Nothing
%>
</body>
</html>

See the following edit in your code -
you create a recordset and then open it and execute it
<html>
<body>
<%
Dim sConnString, connection, sSQL, backgroundColor,objrs
sSQL = "SELECT firstName, lastName, email, zip, country, company, industry, revenue, timestamp FROM users"
Set connection = Server.CreateObject("ADODB.Connection")
connection.connectionstring = "put your connection string in here"
' replace put your connection string in here with your connection string
Set objrs= Server.CreateObject("ADODB.Recordset")
connection.Open()
objrs.open sSQL,connection
Response.Write"<table>"
do while not objrs.EOF
if(backgroundColor="#f1f1f1")then
backgroundColor="#ffffff"
else
backgroundColor="#f1f1f1"
end if
response.write"<tr backgroundColor="& backgroundColor & "></td>" & objrs("firstName") & "</td><td>" & objrs("lastName") & "</td><td>" & objrs("email") & "</td><td>" & objrs("zip") & "</td><td>" & objrs("country") & "</td><td>" & objrs("company") & "</td><td>" & objrs("industry") & "</td><td>" & objrs("revenue") & "</td><td>" & objrs("timestamp") & "</td></tr>"
objrs.MoveNext
Loop
Response.Write"</table>"
%>
</body>
</html>
a note:--
this needs to be something like - not sure what database you are using -
sConnString= "Provider=sqloledb;Data Source=ServerName;Initial Catalog=DatebaseName "
or if you have a dsn connection then simply
sConnString = "DSN=xxxxx;uid=xxx;pwd=xxx"

You will need to create a Recordset to read the data from your SQL query. You have used connection itself.
try below example.
HERE

Related

Asp.net Sql Insert rows using select case

Im designing a website that allows a user to update a database with information. The problem I am having is that I have created various controls that are hidden when the page loads, but the user can click to unhide to add additional info.
The issue I am coming up against is writing the sql statement to handle identifying what controls are used. I have a viewstate count to let me know which panels are visible or not.
ViewState("count") = CInt(ViewState("count")) + 1
Label1.Text = ViewState("count").ToString()
And then the code behind to write the SQL query I have looks like this
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim myConn As SqlConnection
Dim cmd As SqlCommand
Dim sqlstring As String
Dim dd As String
Dim mm As String
Dim yy As String
dd = Left(TextBox1.Text, 2)
mm = Mid(TextBox1.Text, 4, 2)
yy = Right(TextBox1.Text, 4)
myConn = New SqlConnection("xxx")
myConn.Open()
Select Case Label1.Text
Case Is = "0"
sqlstring = "INSERT INTO Transactions (Date, Account, Payee, Chq_Num, Reference, GST_Rate, Amount, Document_Number, Bank_Account) VALUES ('" & yy & "-" & mm & "-" & dd & "','" & DropDownList3.SelectedValue & "','" & TextBox3.Text & "','" & TextBox5.Text & "','" & TextBox4.Text & "'," & DropDownList2.SelectedValue & "," & TextBox6.Text & "," & TextBox27.Text & ",'" & DropDownList1.SelectedValue & "')"
Case Is = "1"
sqlstring = "INSERT INTO Transactions (Date, Account, Payee, Chq_Num, Reference, GST_Rate, Amount, Document_Number, Bank_Account) VALUES ('" & yy & "-" & mm & "-" & dd & "','" & DropDownList3.SelectedValue & "','" & TextBox3.Text & "','" & TextBox5.Text & "','" & TextBox4.Text & "'," & DropDownList2.SelectedValue & "," & TextBox6.Text & "," & TextBox27.Text & ",'" & DropDownList1.SelectedValue & "') VALUES ('" & yy & "-" & mm & "-" & dd & "','" & DropDownList4.SelectedValue & "','" & TextBox7.Text & "','" & TextBox9.Text & "','" & TextBox8.Text & "'," & DropDownList5.SelectedValue & "," & TextBox10.Text & "," & TextBox27.Text & ",'" & DropDownList1.SelectedValue & "')"
End Select
cmd = New SqlCommand(sqlstring, myConn)
cmd.ExecuteNonQuery()
myConn.Close()
Response.Redirect(Request.RawUrl, True)
End Sub
My problem lies in the select case as when case is 1 it is only inserting the first values and not the second set. I have up to 6 "cases" to choose from, each time adding an additional set of values. Sql server is 2008
Any help is appreciated
I may be wrong but in the second statement the clause VALUES appears two two times.
That might be the source of your problem.
as above however you are going to end up with a horribly long string by the 6th case might want to re-engineer it to check >= each value if the previous strings are immutable
From SQL Server 2008 onwards, you can use the multi-values insert clause that looks like this
INSERT [INTO] tbl [(...columns...)]
VALUES (....),(....),(....);
You have constructed your query like this
INSERT [INTO] tbl [(...columns...)]
VALUES (....)
VALUES (....)
VALUES (....)
I would also personally have constructed the string concatenation not using a SELECT-CASE block:
If Label1.Text >= "0" Then
sqlstring = "('" & yy & "-" & mm & "-" & dd & "','" & DropDownList3.SelectedValue & "','" & TextBox3.Text & "','" & TextBox5.Text & "','" & TextBox4.Text & "'," & DropDownList2.SelectedValue & "," & TextBox6.Text & "," & TextBox27.Text & ",'" & DropDownList1.SelectedValue & "')"
End If
If Label1.Text >= "1" Then
sqlstring = sqlstring + "," + "('" & yy & "-" & mm & "-" & dd & "','" & DropDownList4.SelectedValue & "','" & TextBox7.Text & "','" & TextBox9.Text & "','" & TextBox8.Text & "'," & DropDownList5.SelectedValue & "," & TextBox10.Text & "," & TextBox27.Text & ",'" & DropDownList1.SelectedValue & "')"
End If
' etc
If for whatever arcane reason the multi-values statement doesn't work, you can always rely on the tried and true multi-statement batch, i.e.
If Label1.Text >= "0" Then
sqlstring = "INSERT ... VALUES (...);"
End If
If Label1.Text >= "1" Then
sqlstring = sqlstring + "INSERT ... VALUES (...);"
End If
If Label1.Text >= "2" Then
sqlstring = sqlstring + "INSERT ... VALUES (...);"
End If
' etc
Note the semicolon statement terminators within the batch.
The issue was not the select case but the viewstate not passing to the sql string correctly, I know possibly not the best solution but passed the label.text to a hidden textbox, which the sql string was able to read properly. Richard's suggestion to use a concatenated IF statement instead of Select Case was a great idea!
Thanks for all the help

Dynamically create table and insert data in asp.net

Dynamically create table and insert data into the created table, I'm using following command to create a table dynamically and insert the values. I'm commented the sample value for the variable respectively.
Dim question, opt1, opt2, opt3, opt4, ans, paper As String
question = Request.QueryString("question") '<p>This is my first question</p>
opt1 = Request.QueryString("option1") ' option 1
opt2 = Request.QueryString("option2") ' option 2
opt3 = Request.QueryString("option3") ' option 3
opt4 = Request.QueryString("option4") ' option 4
ans = Request.QueryString("answer") ' 2
paper = Request.QueryString("paper") ' cs-5-cder-2012
'Response.Write("....")
Dim cs As String = ConfigurationManager.ConnectionStrings("eExamSolutionConnection").ConnectionString
Dim cn As New SqlConnection(cs)
Dim cmd As New SqlCommand
Dim cmdText As String
cmdText = "IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'RAVI' AND TABLE_NAME = '" & paper & "') "
cmdText = cmdText & " BEGIN"
cmdText = cmdText & " INSERT INTO " & paper & "(question,option1,option2,option3,option4,answer) VALUES('" & question & "','" & opt1 & "','" & opt2 & "','" & opt3 & "','" & opt4 & "','" & ans & "');"
cmdText = cmdText & " END"
cmdText = cmdText & " ELSE"
cmdText = cmdText & " BEGIN"
cmdText = cmdText & " CREATE TABLE " & paper & "(question_Id int AUTO_INCREMENT,question varchar(MAX),option1 varchar(255),option2 varchar(255),option3 varchar(255),option4 varchar(255),answer varchar(2));"
cmdText = cmdText & " INSERT INTO " & paper & "(question,option1,option2,option3,option4,answer) VALUES('" & question & "','" & opt1 & "','" & opt2 & "','" & opt3 & "','" & opt4 & "','" & ans & "');"
cmdText = cmdText & " END"
Try
cmd.CommandText = cmdText.ToString
cmd.Connection = cn
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
cmd.Dispose()
cn.Dispose()
Response.Write("Question Added !!")
Catch ex As Exception
Response.Write(ex.ToString)
End Try
But, I'm getting exception
System.Data.SqlClient.SqlException: Incorrect syntax near '-'. Incorrect syntax near '-'. Incorrect syntax near '-'.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj)
at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String
methodName, Boolean async)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult
result, String methodName, Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at ASP.admin_addquestion_aspx._Render_control1(HtmlTextWriter __w,
Control parameterContainer) in
D:\EWA\eExam\admin\addQuestion.aspx:line 40
Please use
Dim cmdText As String
cmdText = "IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'RAVI' AND TABLE_NAME = '" & paper & "') "
cmdText = cmdText & " BEGIN"
cmdText = cmdText & " INSERT INTO [" & paper & "](question,option1,option2,option3,option4,answer) VALUES('" & question & "','" & opt1 & "','" & opt2 & "','" & opt3 & "','" & opt4 & "','" & ans & "');"
cmdText = cmdText & " END"
cmdText = cmdText & " ELSE"
cmdText = cmdText & " BEGIN"
cmdText = cmdText & " CREATE TABLE [" & paper & "](question_Id int IDENTITY(1,1),question varchar(MAX),option1 varchar(255),option2 varchar(255),option3 varchar(255),option4 varchar(255),answer varchar(2));"
cmdText = cmdText & " INSERT INTO [" & paper & "](question,option1,option2,option3,option4,answer) VALUES('" & question & "','" & opt1 & "','" & opt2 & "','" & opt3 & "','" & opt4 & "','" & ans & "');"
cmdText = cmdText & " END"
Instead of
Dim cmdText As String
cmdText = "IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'RAVI' AND TABLE_NAME = '" & paper & "') "
cmdText = cmdText & " BEGIN"
cmdText = cmdText & " INSERT INTO " & paper & "(question,option1,option2,option3,option4,answer) VALUES('" & question & "','" & opt1 & "','" & opt2 & "','" & opt3 & "','" & opt4 & "','" & ans & "');"
cmdText = cmdText & " END"
cmdText = cmdText & " ELSE"
cmdText = cmdText & " BEGIN"
cmdText = cmdText & " CREATE TABLE " & paper & "(question_Id int AUTO_INCREMENT,question varchar(MAX),option1 varchar(255),option2 varchar(255),option3 varchar(255),option4 varchar(255),answer varchar(2));"
cmdText = cmdText & " INSERT INTO " & paper & "(question,option1,option2,option3,option4,answer) VALUES('" & question & "','" & opt1 & "','" & opt2 & "','" & opt3 & "','" & opt4 & "','" & ans & "');"
cmdText = cmdText & " END"
Problem was:
1 Table name should be[] at create and insert time.
2 For autoincremnet there will be IDENTITY(1,1) in SQL server.
You could try adding [ and ] around the table name, so it would become;
"IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'RAVI' AND TABLE_NAME = ['" & paper & "']) "
Hyphen character "-" is not allowed in table name. You must replace it with either underscore "_" or completely remove it.

Line 0 Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done

I have inherited some code old asp/vb code and its throwing an error which I can't find a fix for.
The server is Windows Server 2008, its running IIS7 and the SQL server is 2008.
This is the code:
<% # Language=VBScript %>
<!-- #include file="dsn.asp" -->
<!-- #include file="adovbs.inc" -->
<!-- #include file="libfunct.asp" -->
<%
'****************************************
' VARIABLES DECLARATION
'****************************************
Dim sSql, RsInsCoInfo, PolicyID, InsCo, InsOffice
Dim qsPolicyType, qsAttach, qsCLNT_ID, qsClientID
Dim CostArray(10)
Dim DescriptionArray(10)
'****************************************
' END VARIABLES DECLARATION
'****************************************
'********************************************
' RETRIEVING THE QUERYSTRINGS
'********************************************
qsAttach = Request.QueryString("Attach")
qsCLNT_ID = Request.QueryString("CLNT_ID")
qsClientID = Request.QueryString("ClientID")
qsPolicyType = Request.QueryString("PolicyType")
qsReQuote = Request.QueryString("ReQuote")
qsPolicyID = Request.QueryString("PolicyID")
'********************************************
' END RETRIEVING THE QUERYSTRINGS
'********************************************
'**********************************************
' RETRIEVING THE INSURANCE COMPANY DETAILS
'**********************************************
'Get the insurance company details
Set RsInsCoInfo = Server.CreateObject("ADODB.RecordSet")
sSQL = "SELECT InsuranceCo.*,FormPolicy.* FROM insuranceCo,FormPolicy"
sSQL = sSQL & " WHERE FormPolicy.INS_EF <= CONVERT(smalldatetime,'" & dbSaveDate(Date) & "',101)"
sSQL = sSQL & " And FormPolicy.INS_ET >= convert(smalldatetime,'" & dbSaveDate(Date) & "',101)"
sSQL = sSQL & " AND FormPolicy.PolicyType ='" & qsPolicyType & "'"
sSQL = sSQL & " AND InsuranceCo.INS_ID = FormPolicy.INS_ID"
'response.write ssql
'response.end
RsInsCoInfo.Open sSQL, OLEDBConnStr, adOpenStatic, adLockReadOnly, adCmdText
If Not RsInsCoInfo.EOF then
InsOffice = RsInsCoInfo("INS_Office")
InsCo = RsInsCoInfo("INS_DS")
Else
Response.write "<b>No underwriter available. Please contact the system administrator.<br>"
Response.write sSQL
Response.end
End if
'Close and free
RsInsCoInfo.close
Set RsInsCoInfo = Nothing
'**********************************************
' END RETRIEVING THE INSURANCE COMPANY DETAILS
'**********************************************
'*********************************************************************************
' CLIENT SEQUENCE NUMBER INCREMENT FOR THIS POLICY TYPE
'*********************************************************************************
If Not qsReQuote Then
newPolicyNumber = qsClientID & qsPolicyType
Set RsSequence = Server.CreateObject("ADODB.RecordSet")
sSQL = "SELECT * FROM Policy WHERE PolicyNumber like '%" & newPolicyNumber & "%' AND Clnt_ID=" & qsCLNT_ID
RsSequence.Open sSQL, OLEDBConnStr, adOpenStatic, adLockReadOnly, adCmdText
If RsSequence.recordcount > 0 then
PolicyID = 00
While not RsSequence.eof
If right(RsSequence("PolicyNumber"), 2) > PolicyID then
PolicyID = Cstr(right(RsSequence("PolicyNumber"), 2))
response.write PolicyID & "<br>"
End if
RsSequence.moveNext
Wend
PolicyID = PolicyID + 1
If PolicyID < 10 then
PolicyID = "0" & CStr(PolicyID)
End If
Else
PolicyID = "01"
End If
RsSequence.close
SET RsSequence = NOTHING
End If
'*********************************************************************************
' END CLIENT SEQUENCE NUMBER INCREMENT FOR THIS POLICY TYPE
'*********************************************************************************
'*********************************************************************************
' UPDATING ADDITIONNAL FIELD TO THE QUOTE CREATION
'*********************************************************************************
'Setting var
Dim strConnection, SQL_Upsate, newPolicyNumber
newPolicyNumber = qsClientID & qsPolicyType & PolicyID
If Not qsReQuote Then
'Insert Sql Statement
SQL_Update = "UPDATE Policy SET CLNT_ID=" & qsCLNT_ID & ","
SQL_Update = SQL_Update & " InsuranceCo='"& InsCo & "',"
SQL_Update = SQL_Update & " Office='"& InsOffice & "',"
SQL_Update = SQL_Update & " StatusID="& 0 & ","
SQL_Update = SQL_Update & " PolicyNumber='" & newPolicyNumber & "'"
SQL_Update = SQL_Update & " WHERE PolicyID=" & qsAttach
Else
'Insert Sql Statement
SQL_Update = "UPDATE Policy SET CLNT_ID=" & qsCLNT_ID & ","
SQL_Update = SQL_Update & " InsuranceCo='"& InsCo & "',"
SQL_Update = SQL_Update & " Office='"& InsOffice & "',"
SQL_Update = SQL_Update & " StatusID="& 0
SQL_Update = SQL_Update & " WHERE PolicyID=" & qsPolicyID
End If
'Connection object and open the db
Set strConnection = Server.CreateObject("ADODB.Connection")
strConnection.Open OLEDBConnStr
' Executing the sql insert
strConnection.Execute SQL_Update
'Now Close the connection and free up
strConnection.Close
Set strConnection = Nothing
'*********************************************************************************
' END ADDING ADDITIONAL FIELDS TO THE QUOTE CREATION
'*********************************************************************************
'*********************************************************************************
' DO CALCULATION
' - obtains file named Policy & 'Calculations.inc' = HHCalculations.inc etc.
'
' Modified by Stuart 20/5/03
'*********************************************************************************
set Rs = Server.CreateObject("ADODB.Recordset")
If Not qsReQuote Then
sSQL = "SELECT Policy.* FROM Policy WHERE Policy.PolicyID=" & qsAttach
Else
sSQL = "SELECT Policy.* FROM Policy WHERE Policy.PolicyID=" & qsPolicyID
End If
Rs.Open sSQL, OLEDBConnStr, adOpenkeyset, adLockPessimistic, adCmdText
'********************************************
'Response.write "<B>Policy table For Testing Only<P></b>"
'For Each fld in Rs.fields
' Response.write fld.name & " = " & fld.value & "<br>"
'Next
'Response.end
'**********************************************
Agent = 0
Agent2 = 0
AgentIntro = 0
'Open rsAccount for writing account entries to the PolicyAmount table
'** Comment derek to Stuart -> wont we be better here to find the agent with the code?
If Session("Agent") <> "" then
set RsAgent = Server.CreateObject("ADODB.Recordset")
sSQL = "Select * from Agents Where Name = '" & Session("Agent") & "'"
RsAgent.Open sSQL, OLEDBConnStr, adOpenkeyset, adLockPessimistic, adCmdText
Agent = rsAgent("commission")
End if
'If a park was involved for a new business then the introductory rate is required.
If Session("Village_Name") <> "" then
set RsPark = Server.CreateObject("ADODB.Recordset")
If IsNumeric(Session("Village_Name")) Then
sSQL = "Select * from Park Where ParkID = '" & Session("Village_Name") & "'"
Else
sSQL = "Select * from Park Where ParkID = '" & Session("reParkID") & "'"
End If
RsPark.Open sSQL, OLEDBConnStr, adOpenkeyset, adLockPessimistic, adCmdText
If RsPark.eof then
Response.write "<b>" & ssql & "<P>No Park record found - Line 189 QuoteSave2.asp<P>Please contact you system administrator."
'Response.end
Else
AgentIntro = RsPark("Introduction")
End if
End if
set RsAccount = Server.CreateObject("ADODB.Recordset")
set RsQuestions = Server.CreateObject("ADODB.Recordset")
If Not qsReQuote Then
sSQL = "SELECT * FROM PolicyAmount WHERE PolicyID=" & qsAttach
Else
sSQL = "SELECT * FROM PolicyAmount WHERE PolicyID=" & qsPolicyID
End If
RsAccount.Open sSQL, OLEDBConnStr, adOpenkeyset, adLockPessimistic, adCmdText
If Not qsReQuote Then
sSQL = "SELECT * FROM PolicyQuestions WHERE PolicyID=" & qsAttach
Else
sSQL = "SELECT * FROM PolicyQuestions WHERE PolicyID=" & qsPolicyID
End If
RsQuestions.Open sSQL, OLEDBConnStr, adOpenkeyset, adLockPessimistic, adCmdText
If Not qsRequote Then
RsAccount.Addnew
End If
If Not qsRequote Then
RsAccount("PolicyID") = qsAttach
linkID = qsAttach
Else
RsAccount("PolicyID") = qsPolicyID
linkID = qsPolicyID
End If
sTargetFile = qsPolicyType & "Calculations.inc"
sTargetFileContents = GetFileContentsForExecution(sTargetFile)
Execute sTargetFileContents
'*********************************************************************************
' END DO CALCULATION
'*********************************************************************************
'*********************************************************************************
' WRITE COSTS TO THE TABLE
'*********************************************************************************
'Update data to the PolicyAmount table
RsAccount("PolicyAmount_IB") = Session("Login")
RsAccount("PolicyAmount_IT") = Date
RsAccount.Update
'**********************************************
'Response.write "<P><B>PolicyAmount table For Testing Only<P></b>"
'For Each fld in RsAccount.fields
' Response.write fld.name & " = " & fld.value & "<br>"
'Next
'Response.write "<P><B><a href='default.asp'>Home</a>"
'Response.end
'***********************************************
'Clean up
RsAccount.Close
Set RsAccount = Nothing
Rs.update
Rs.Close
Set Rs = Nothing
RsQuestions.Close
Set RsQuestions = Nothing
'RsPark.close
'Set RsPark = Nothing
'Finish with this second saving so redirect to the policy page
If Not qsReQuote Then
Response.redirect "Policy.asp?PolicyID=" & qsAttach & "&CLNT_ID=" & qsCLNT_ID & "&ClientID=" & qsClientID & "&PolicyType=" & qsPolicyType
Else
Response.redirect "Policy.asp?PolicyID=" & qsPolicyID & "&CLNT_ID=" & qsCLNT_ID & "&ClientID=" & qsClientID & "&PolicyType=" & qsPolicyType
End If
%>
This is the error: "Warning: File /quotesave2.asp Line 0 Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.. ."
It really doesn't give me much to go on and any help/insight would be greatly appreciated.
Thanks.
It's real tough to pin down the exact issue with no line number. I noticed towards the end of the script, you are adding a new record to RsAccount and assigning values to the recordset fields. In the past, I have gotten the "Multiple-step OLE DB operation generated errors" error due to type mismatches between the VBScript variable and the recordset field type. Double-check the data type of the columns that you are updating, and if necessary, explicitly convert values before assigning them to the recordset (for example, using CLng for numbers).
This is classic, i handle these problems by logging each command to the db just before executing. So eg
log(sSql)
RsAccount.Open sSQL, OLEDBConnStr, adOpenkeyset, adLockPessimistic, adCmdText
Where log(tekst) is a sub which writes to a txt file the passed text. Now when you encounter an error execution stops and you check your log. The last entry is the sql generating the error. Execute this sql in an interactive environment where you can easily adjust the text and try again and where you get more accurate error from your dbclient. Don't know what it is for Sql Server, i use Oracle and there it is Sql*Plus, i'm sure there must be others for Sql Server. Once you corrected your sql, paste it in your code, replacing your literals with variables. Request your page again and do the above until all your sql is correct.
First, your SELECT statement is selecting multiple field with same name which might cause a problem. Change your statement to this: (You might need to change the table of INS_DS, I just guessed)
sSQL = "SELECT ic.INS_Office, fp.INS_DS "&_
"FROM insuranceCo ic INNER JOIN FormPolicy fp ON ic.INS_ID = fp.INS_ID "&_
"WHERE fp.INS_EF <= CONVERT(smalldatetime,'" & dbSaveDate(Date) & "',101) "&_
"AND fp.INS_ET >= convert(smalldatetime,'" & dbSaveDate(Date) & "',101) "&_
"AND fp.PolicyType = '" & qsPolicyType & "'"
If still same error, I remember getting this one when messing around with Date/Time fields so those two date fields are suspects. For sake of debug try to select without that filter and see what happens:
sSQL = "SELECT ic.INS_Office, fp.INS_DS "&_
"FROM insuranceCo ic INNER JOIN FormPolicy fp ON ic.INS_ID = fp.INS_ID "&_
"WHERE fp.PolicyType = '" & qsPolicyType & "'"

Insert into Access DB (loop)

I have this code and its coming up with an INSERT INTO statement error...
Its probably something but I have been at it for a while... please help.
'Add items to db'
Function recordOrder()
objDT = Session("Cart")
Dim intCounter As Integer
For intCounter = 0 To objDT.Rows.Count - 1
objDR = objDT.Rows(intCounter)
Dim con2 As New System.Data.OleDb.OleDbConnection
Dim myPath2 As String
myPath2 = Server.MapPath("faraxday.mdb")
con2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data source=" & myPath2 & ";"
Dim myCommand2 As New System.Data.OleDb.OleDbCommand
myCommand2.CommandText = "INSERT INTO order(order_date, coupon_id, customer_id, quantity) values('" & System.DateTime.Now & "','" & Int32.Parse(objDR("ID")) & "','" & Int32.Parse(custID) & "','" & Int32.Parse(objDR("quantity")) &"')"
myCommand2.Connection = con2
con2.Open()
myCommand2.ExecuteReader()
con2.Close()
test.Text += "Order ID: " & objDR("ID") & "Order Date: " & System.DateTime.Now & ", Cust ID: " & custID & ", Quantity: " & objDR("quantity") &" "
Next
End Function
I think you are getting an error by not enclosing the Date inside Pound signs. You have to do this in Jet (Access) when using variables not parameters.
VALUES('#" & DateTime.Now.Date & "#',...
I also took the liberty of refactoring this code for you since you are creating a new connection for each record which is bad news. Use a Try Catch Finally block and move all that stuff outside the For Loop (please see below)
Function recordOrder()
objDT = Session("Cart")
Dim intCounter As Integer
Dim con2 As New System.Data.OleDb.OleDbConnection
Dim myPath2 As String
myPath2 = Server.MapPath("faraxday.mdb")
con2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" <-- etc
Dim myCommand2 As New System.Data.OleDb.OleDbCommand
myCommand2.Connection = con2
con2.Open()
Try
For intCounter = 0 To obDT.Rows.Count - 1
objDR = objDT.Rows(intCounter)
myCommand2.CommandText = "INSERT INTO order(order_date,coupon_id,customer_id,quantity)" _
& "VALUES ('#" & System.DateTime.Now.Date & "#','" & Int32.Parse(objDR("ID")) & "','" & Int32.Parse(custID) _
& "','" & Int32.Parse(objDR("quantity")) & "')"
myCommand2.ExecuteReader()
Next
Catch ex As Exception
'handle errors here
Finally
If con2.State = ConnectionState.Open Then
con2.Close()
End If
End Try
End Function
Remember to mark as answered if this helps.
I've sorted it out by removing the single quotes. Thanks everybody to contributed to this.

What was the problem in this query?

Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT [counts] FROM [a1_holds] WHERE (dates ='" & TextBox1.Text & "' BETWEEN from_date AND to_date) AND service ='" & lab5.Text & "' ORDER BY [id] ASC", SQLData)
ERROR :incorrect syntax near BETWEEN
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT [counts] FROM [a1_holds] WHERE ('" & TextBox1.Text & "' BETWEEN from_date AND to_date) AND service ='" & lab5.Text & "' ORDER BY [id] ASC", SQLData)
WHERE (dates = '...' BETWEEN ... AND ...)
is a syntax error. Either: ('...' BETWEEN ... AND ...) or (dates = '...')

Resources