Solved

Parameterized SQL Help

Posted on 2014-03-07
4
294 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 33

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

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Let's review the features of new SQL Server 2012 (Denali CTP3). It listed as below: PERCENT_RANK(): PERCENT_RANK() function will returns the percentage value of rank of the values among its group. PERCENT_RANK() function value always in be…
Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

740 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