Error executing sql expression ASP - sql

I'm attempting to use a variable for the column field in the SQL statement however it shoots back the following error at me:
Microsoft OLE DB Provider for ODBC Drivers error '80040e14'
[Microsoft][ODBC Text Driver] Syntax error (missing operator) in query expression '= 'Yes''.
/junk/dbresults.htm, line 31
THE CODE:
<%
Dim connectString, connect, conDB, con
connectString = "Driver={Microsoft Text Driver (*.txt; *.csv)}; DBQ=" & Server.MapPath("data")
src_abn = Request.QueryString("abn")
src_cat = Request.QueryString("cat")
set connect = Server.CreateObject("ADODB.connection")
connect.open connectString
if src_abn = "all" then
conDB = "SELECT * FROM cont.csv WHERE " & src_cat & " = 'Yes'"
else
conDB = "SELECT * FROM cont.csv WHERE ucase(abn) LIKE ucase('%"+src_abn+"%')"
end if
set con = connect.execute(conDB)
%>

Looks like the value of src_cat contains spaces or other characters that create an invalid query. Try changing that line to this (with brackets):
conDB = "SELECT * FROM cont.csv WHERE [" & src_cat & "] = 'Yes'"

Fixed it, the variables were not delcared.

Related

Incorrect syntax near 's'. Unclosed quotation mark after the character string

I'm using a query to pull data from an SQL database, at times the last dropdown im using to get the record i'm looking for has a single quote, when it does I get the following error: Incorrect syntax near 's'. Unclosed quotation mark after the character string
This is the code I have:
Using objcommand As New SqlCommand("", G3SqlConnection)
Dim DS01 As String = DDLDS01.SelectedItem.Text
Dim State As String = DDLState.SelectedItem.Text
Dim Council As String = DDLCouncil.SelectedItem.Text
Dim Local As String = DDLLocal.SelectedItem.Text
Dim objParam As SqlParameter
Dim objDataReader As SqlDataReader
Dim strSelect As String = "SELECT * " & _
"FROM ConstitutionsDAT " & _
"WHERE DS01 = '" & DS01 & "' AND STATE = '" & State & "' AND COUNCIL = '" & Council & "' AND LOCAL = '" & Local & "' AND JURISDICTION = '" & DDLJurisdiction.SelectedItem.Text & "' "
strSelect.ToString.Replace("'", "''")
objcommand.CommandType = CommandType.Text
objcommand.CommandText = strSelect
Try
objDataReader = objcommand.ExecuteReader
DDLJurisdiction.Items.Add("")
While objDataReader.Read()
If Not IsDBNull(objDataReader("SUBUNIT")) Then
txtSubUnit.Text = (objDataReader("SUBUNIT"))
End If
If Not IsDBNull(objDataReader("DS02")) Then
lblDS02.Text = (objDataReader("DS02"))
End If
If Not IsDBNull(objDataReader("LEGISLATIVE_DISTRICT")) Then
txtALD.Text = (objDataReader("LEGISLATIVE_DISTRICT"))
End If
If Not IsDBNull(objDataReader("REGION")) Then
txtRegion.Text = (objDataReader("REGION"))
End If
If DDLState.SelectedItem.Text <> "OTHER" Then
If Not IsDBNull(objDataReader("UNIT_CODE")) Then
txtUnitCode.Text = (objDataReader("UNIT_CODE"))
End If
End If
End While
objDataReader.Close()
Catch objError As Exception
OutError.Text = "Error: " & objError.Message & objError.Source
Exit Sub
End Try
End Using
Not all records contain a single quote, only some, so i'd need something that would work if a single quote is present or not.
Thanks.
Your problem is this line here:
strSelect.ToString.Replace("'", "''")
This is changing your WHERE clause from something like
WHERE DS01 = 'asdf' AND ...
To:
WHERE DS01 = ''asdf'' AND ...
You need to do the replace on the individual values in the where clause, not on the whole select statement.
What you should really be doing is using a parameterized query instead.
Update: added same link as aquinas because it's a good link
Use parameterized queries, and only EVER use parameterized queries. See: How do I create a parameterized SQL query? Why Should I?

'if exist' SQL query in VBA with ADODB database connection

I need to uplad data from excel into a database, but I need to check first if there is data in the table for each upload so that I Update or Insert data.
To diferentiate Update or Insert, I'm usign a SQL IF EXIST command, which works okay in SQL. When I try this in Excel VBA I get an error message: "Command text was not set for the command object."
See code below
Dim strSQL As String
Dim Value As String
Dim Reference As String
Set RCconn = New ADODB.Connection
Set TuneCMD = New ADODB.Command
' Establish Recordset
Set Results = New ADODB.Recordset
'Establish a Connection
With RCconn
.Provider = "SQLOLEDB"
.ConnectionString = ConStr
End With
'Open the connection
RCconn.Open
'i Columns
For i = 5 To 10 '16
'j rows
For j = 6 To 60 '145
Value= Sheets("Value").Cells(j, i)
Reference= "W_F/P_" & Sheets("Reference").Cells(j, i)
stringTest = "IF EXISTS (SELECT * FROM UploadTable WHERE Ref = '" & Reference & "') "
stringTest = stringTest & "UPDATE Val "
stringTest = stringTest & "SET Val = '" & Value & "' "
stringTest = stringTest & "where Ref = '" & Reference & "' "
stringTest = stringTest & "Else "
stringTest = stringTest & "INSERT INTO UploadTable (Val , Ref ) "
stringTest = stringTest & "values ('" & Value & "', '" & Reference & "')"
RCconn.Execute strSQL
Next
Next
Set Results = Nothing
RCconn.Close
Set RCconn = Nothing
Is it the case that 'IF EXIST' can not be used in VBA? Is there a work around?
Thanks
ADODB.Connection.Execute sends a pass-through query to your database. It doesn't matter what SQL statement was in that string; if your database can understand it, it will be executed.
So inspect your SQL query again.
Try this:
Put a breakpoint on the line RCconn.Execute strSQL. When the debugger breaks there, inspect the value of strSQL. Copy it and execute in SQL Server Management Studio directly. If that doesn't work, correct your code that builds that string. If it works, then there is some problem with your ConnectionString. In that case, check that the userID and password you are using in the ConnectionString to connect has adequate privileges.

Invalid Character error (ADO/ASP)

I am trying to use a variable as the column field in the SQL. However when I run the code I get the following error:
Microsoft VBScript compilation error '800a0408'
Invalid character
/junk/dbresults.htm, line 25
DECLARE #cat char(20)
--------^
The code is below:
<%
Dim connectString, connect, conDB, con
connectString = "Driver={Microsoft Text Driver (*.txt; *.csv)}; DBQ=" & Server.MapPath("data")
src_abn = Request.QueryString("abn")
src_cat = Request.QueryString("cat")
set connect = Server.CreateObject("ADODB.connection")
connect.open connectString
DECLARE #cat char(20)
DECLARE #dynamicsql char(1000)
SET #cat = src_cat;
SET #dynamicsql = "SELECT * FROM cont.csv WHERE #cat='Yes'"
if src_abn = "all" then
conDB = EXEC (#DynamicSQL)
else
conDB = "SELECT * FROM cont.csv WHERE ucase(abn) LIKE ucase('%"+src_abn+"%')"
end if
set con = connect.execute(conDB)
%>
I'm not positive what you're trying to do, but you can't run SQL Syntax (i.e. DECLARE #cat...) with classic ASP. Are you trying to do something like this?
<%
//Request your variables
src_abn = Request.QueryString("abn")
src_cat = Request.QueryString("cat")
Dim connectionString, dbConn, rsResults, strSQL
//Setup your connection
connectionString = "Driver={Microsoft Text Driver (*.txt; *.csv)}; DBQ=" & Server.MapPath("data")
set dbConn= Server.CreateObject("ADODB.Connection")
dbConn.open connectionString
//Create your sql statement
if src_abn = "all" then
strSQL = "SELECT * FROM cont.csv WHERE " & src_cat & "='Yes'"
else
strSQL = "SELECT * FROM cont.csv WHERE ucase(abn) LIKE ucase('%" & src_abn & "%')"
end if
//Create your results
set rsResults = Server.CreateObject("ADODB.Recordset")
rsResults.open strSQL, dbConn
//Loop through your results
While Not rsResults.EOF
rsResults.MoveNext
Wend
//Closes results and connection
rsResults.Close
dbConn.Close
%>

VB.NET: convert text with single quote to upload to Oralce DB

I have a function in VB.NET that runs a query from an MS SQL DB, puts the results into temporary variables, then updates an Oracle DB. My question is, if the string in the MS SQL contains a single quote ( ' ), how do I update the Oracle DB for something that has that single quote?
For example: Jim's request
Will produce the following error: ORA-01756: quoted string not properly terminated
The ueio_tmpALM_Comments (coming from MS SQL) is the culprit that may or may not contain the single quote.
update_oracle =
"update Schema.Table set ISSUE_ADDED_TO_ALM = '1'," & _
"ISSUE_COMMENTS = '" & ueio_tmpALM_Comments & "'," & _
"where ISSUE_SUMMARY = '" & ueio_tmpALM_Summary & "' "
Dim or_cmd_2 = New NetOracle.OracleCommand(update_oracle, OracleConn)
or_cmd_2.ExecuteNonQuery()
From your question it's clear that you are building the update query using string concatenation.
Something like this
Dim myStringVar as string = "Jim's request"
Dim sqlText as String = "UPDATE MYTABLE SET MYNAME = '" + myStringVar + "' WHERE ID = 1"
this is a cardinal sin in the SQL world. Your code will fail for the single quote problem, but the most important thing is that this code is subject to Sql Injection Attacks.
You should change to something like this
Dim cmd As OraclCommand = new OracleCommand()
cmd.Connection = GetConnection()
cmd.CommandText = "UPDATE MYTABLE SET MYNAME = :myName WHERE ID = 1"
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue(":myName", myStringVar)
cmd.ExecuteNonQuery()

sql Server error - 3709

Hi I keep getting the error:
Error (3709) - /mysite/Pages_Secure/mypage.asp ADODB.Recordset.
"The connection cannot be used to perform this operation. It is either closed or invalid in this context.."
strQuery = ""
strQuery = strQuery + "SET ROWCOUNT 0 "
strQuery = strQuery + "SELECT FIRSTNAME, LASTNAME, EMAIL, USER_TEAM_ID, USER_SERVICE_ID, USER_DIRECTORATE_ID "
strQuery = strQuery + "FROM Web_Users "
strQuery = strQuery + "WHERE USER_ID = '" + Cstr(lOwnerID) + "'"
CALL subOpenConnection("", "")
Set RS = Server.CreateObject("ADODB.RecordSet")
RS.Open strQuery, objDBConnection
Error happens here after the open....
SUB subOpenConnection( strErrorPage, strErrorQueryArguments )
Set objDBConnection = Server.CreateObject("ADODB.Connection")
objDBConnection.ConnectionTimeout = Application("ConnectionTimeout")
objDBConnection.CommandTimeout = Application("CommandTimeout")
objDBConnection.CursorLocation = Application("CursorLocation")
objDBConnection.Open Application("ConnectionString")
END SUB
Any ideas?
I think it's because you're using SUB rather than FUNCTION. The sub won't return the connection object (which is why you get an error that it's closed), whereas a function can return the connection object. Does this sub work anywhere else? Or is this the only time it's used?
ok managed to get this working...can't quite remember how - but was something i had missed! D'oh!