remiremi
remiremi

Reputation: 39

Is it possible to use named parameters when command type is adCmdText?

I'm trying to use named parameters with following query through Adodb.Command but no luck.

Select * From mytable Where col1 = Lower(@param1) And col2 = Upper(@param2) And col3 = @param1

The code I used something like that.

Dim cmd
Set cmd = Server.CreateObject("Adodb.Command")
cmd.NamedParameters = True
cmd.CommandType = adCmdText
cmd.CommandText = "Select * From mytable Where col1 = Lower(@param1) And col2 = Upper(@param2) And col3 = @param1"
cmd.Parameters.Append cmd.CreateParameter("@param1", adVarchar, adParamInput, 20, "some text 1")
cmd.Parameters.Append cmd.CreateParameter("@param2", adVarchar, adParamInput, 20, "some text 2")
Set cmd.ActiveConnection = cn
Dim rs
Set rs = cmd.Execute

The problem is that, this causes an error on RDBMS side.

Microsoft OLE DB Provider for SQL Server error '80040e14'

Must declare the scalar variable "@param1".

There's no any trouble if the query is a stored procedure call. So, I guess namedparameters affects for only command objects which calls stored procedures.
When I track the query using SQL Server Profiler, I saw just the following queries ran (note that, no parameter declaration, no value assignment).

SQL:BatchStarting   Select * From mytable Where col1 = Lower(@param1) And col2 = Upper(@param2)
SQL:BatchCompleted  Select * From mytable Where col1 = Lower(@param1) And col2 = Upper(@param2)

However I need to do it on native vary queries. How can I do it, what is the best practice doing that without string concatenation etc. I don't want to prepare queries with question marks, and I don't like passing parameters with order (it's necessary with question marks and without named parameters) and multiple times. Any help would be greatly appreciated.

Update on misunderstandings: I am looking for a general solution that is not depending on the database.

Upvotes: 2

Views: 7079

Answers (1)

Cheran Shunmugavel
Cheran Shunmugavel

Reputation: 8459

You can't use named parameters with ad-hoc queries in OLE DB. If you're using SQL Server, you could do something like this:

Dim sql
sql = ""
sql = sql & "DECLARE @param1 varchar(20) = ?;"
sql = sql & "DECLARE @param2 varchar(20) = ?;"
sql = sql & "Select * From mytable Where col1 = Lower(@param1) And col2 = Upper(@param2) And col3 = @param1;"

' This section is basically the same as in the original question
Dim cmd
Set cmd = Server.CreateObject("Adodb.Command")
cmd.CommandType = adCmdText
cmd.CommandText = sql
cmd.Parameters.Append cmd.CreateParameter("@param1", adVarchar, adParamInput, 20, "some text 1")
cmd.Parameters.Append cmd.CreateParameter("@param2", adVarchar, adParamInput, 20, "some text 2")
Set cmd.ActiveConnection = cn
Dim rs
Set rs = cmd.Execute

You still have to bind the parameters positionally, but this way, the correct order is easier to see and you can use the same parameter in multiple locations.

Upvotes: 10

Related Questions