Search code examples
sql-servervbscriptasp-classicadonamed-parameters

ADO parameterised query not returning any result


I am using this query to get some results from my vbscript in a classic asp page and It does not come back with any values. The page is blank and there are no errors too. Any suggestion please?

dim cmd, admin_no
admin_no = request.QueryString("admin")

set cmd = server.CreateObject("ADODB.Command")
cmd.ActiveConnection = con
sql = ""
sql = sql & "DECLARE @admin_no int;"
sql = sql & "SELECT field1, field2 FROM mydb.mytable where admin_no = @admin_no"
cmd.CommandText = sql
cmd.CommandType = adCmdText
cmd.Parameters.Append cmd.CreateParameter("@admin_no", adInteger, adParamInput, , admin_no)

'response.write(cmd.Parameters(0))
'response.write(cmd.CommandText)

set rs = server.CreateObject("ADODB.Recordset") 
rs.Open cmd

Solution

  • Problem here is adCmdText uses ? placeholder for passing parameters, change the line

    sql = sql & "SELECT field1, field2 FROM mydb.mytable where admin_no = @admin_no"
    

    to

    sql = sql & "SELECT field1, field2 FROM mydb.mytable where admin_no = ?"
    

    If you are wanting to pass named parameters to your query you don't have too many options but this little trick is useful.

    sql = ""
    sql = sql & "DECLARE @admin_no int;"
    sql = sql & "SET @admin_no = ?;"
    sql = sql & "SELECT field1, field2 FROM mydb.mytable where admin_no = @admin_no"
    

    Useful Links