Solved

Parameterized SQL Help

Posted on 2014-03-07
4
286 Views
Last Modified: 2014-03-26
I have a SQL query that runs fine against the database, but when I try to turn it into parameterized SQL to run in classic ASP, I get an error.

First, here's the db environment:

CREATE TABLE #pies (
ID int,
Name varchar(20),
Available bit)

INSERT INTO #pies
VALUES (1, 'Apple', 1), (2, 'Blueberry', 0), (3,'Cherry',0)

CREATE TABLE #pieorders (
OrderId int,
PieId int)

INSERT INTO #pieorders
VALUES (1,3),(2,2),(3,1)

And here's the raw SQL, where I'm trying to get a list of pies that are either currently available or were ordered in a particular Pie Order (in the below example, order #1):

SELECT P.[ID], P.[Name], PO.[orderid]
FROM #pies P
LEFT OUTER JOIN #pieorders PO ON PO.[PieId]=P.[ID] AND PO.[OrderID] = 1
WHERE P.[Available] = 1 OR PO.[orderid] IS NOT NULL
ORDER BY P.[Name]

When I run it directly against the db, I get:
1, Apple, NULL
3, Cherry, 1
Which is correct.

Here it is in ASP, where I pass in the Pie Order ID:
SQL = "SELECT P.[ID], P.[Name], PO.[orderid] "&_
"FROM #pies P "&_
"LEFT OUTER JOIN #pieorders PO ON PO.[PieId]=P.[ID] AND PO.[OrderID] = ? "&_
"WHERE P.[Available] = 1 OR PO.[orderid] IS NOT NULL "&_
"ORDER BY P.[Name] "
set oCmdPie = Server.CreateObject("ADODB.Command")
oCmdPie.ActiveConnection = conn
oCmdPie.CommandText = SQL
oCmdPie.Parameters(0).value = 1
Set rstPie = oCmdPie.Execute()

It breaks on oCmdPie.Parameters(0).value = 1. I get an error message:
Microsoft OLE DB Provider for SQL Server: Syntax error or access violation

How can I refactor this so it doesn't break?

Please note: although I have given a simplified test environment, this is NOT a homework problem.  I need an answer that will not break and will return the same answers as the current raw query. Thank you!
0
Comment
Question by:EffinGood
  • 2
4 Comments
 
LVL 32

Assisted Solution

by:Big Monty
Big Monty earned 125 total points
ID: 39914100
here's how I like to code my parameterized queries. It's a bit neater and easier to read, along side that it usually gives me better error messages when I break something :) I've coded it to match your sql:

    set rs = Server.CreateObject("ADODB.RecordSet")
    set conn = Server.CreateObject("ADODB.Connection")
    set cmd = Server.CreateObject("ADODB.Command")
    conn.Open connectionString 

     orderID = 1
    SQL = "SELECT P.[ID], P.[Name], PO.[orderid] "&_
"FROM #pies P "&_
"LEFT OUTER JOIN #pieorders PO ON PO.[PieId]=P.[ID] AND PO.[OrderID] = ? "&_
"WHERE P.[Available] = 1 OR PO.[orderid] IS NOT NULL "&_
"ORDER BY P.[Name] "
    with cmd
        .ActiveConnection = conn
        .CommandText = sql
        .Parameters.Append  .CreateParameter( "orderID", adVarChar, adParamInput, , orderID )
    end with
    rs.Open cmd

Open in new window


you will need a copy of adovbs.inc and include it at the top of your page
0
 
LVL 75

Assisted Solution

by:Anthony Perkins
Anthony Perkins earned 250 total points
ID: 39914123
In order to use a Collection you first have to Create it.  So there is nothing wrong with your SQL code (as you have confirmed)  and all you have to do is something like this:
Set oCmdPie = Server.CreateObject("ADODB.Command")
oCmdPie.ActiveConnection = conn
oCmdPie.CommandText = SQL
oCmdPie.Parameters.Append oCmdPie.CreateParameter("OrderID", 3, 1, 4, 1)
Set rstPie = oCmdPie.Execute()

Open in new window

0
 
LVL 52

Assisted Solution

by:Carl Tawn
Carl Tawn earned 125 total points
ID: 39917120
The problem isn't down to the parametrised query, it's down to the fact that you are creating a temp table.

Temps tables only exist within the database session in which they were created, hence it works when you run it in SSMS. When you run the query from ASP, you are running in a different session, so the temp tables aren't available.

To do what you want, you need to use persistent tables in your database instead. In other words, lose the # from the start of the table names when you create them.
0
 
LVL 75

Accepted Solution

by:
Anthony Perkins earned 250 total points
ID: 39918388
Ah, good point.  I missed that.

EffinGood,
In order for it to function as is in ASP the entire script has to run, just the same as in SSMS and not just the SELECT.  Let me know if you need help with that.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

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 …
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

759 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

18 Experts available now in Live!

Get 1:1 Help Now