Reputation: 1333
Having two tables:
MyTable1:
id AutoNumber
typecode Text
MyTable2
id AutoNumber
pid Number
freq Number
using System.Data.OleDb;
namespace AccessSelect
{
class Program
{
static void Main(string[] args)
{
var sql = @"select 'x' from mytable1 where typecode=@typeCode and EXISTS (
select 'x' from mytable2 where (freq=0 OR freq=@freq) and mytable1.id=mytable2.pid)";
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=gpi.mdb;Jet OLEDB:Database Password=???"))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.Add(new OleDbParameter("@typeCode", "KK3000"));
cmd.Parameters.Add(new OleDbParameter("@freq", 50));
var o = cmd.ExecuteScalar();
}
}
}
}
I keep getting the exception 'Data type mismatch in criteria expression.'
If I change the SQL to contain the values:
select 'x' from mytable1 where typecode='KK3000' and EXISTS (
select 'x' from mytable2 where (freq=0 OR freq=50) and mytable1.id=mytable2.pid)
I don't get the error....
Any idea to what is wrong?
Upvotes: 2
Views: 181
Reputation: 1333
Changed it to:
static void Main(string[] args)
{
var sql = @"select 'x' from mytable1 where typecode=@typeCode and EXISTS (
select 'x' from mytable2 where (freq=0 OR freq=@freq) and mytable1.id=mytable2.pid)";
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=gpi.mdb;Jet OLEDB:Database Password=???"))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.Parameters.Add(new OleDbParameter("@freq", 50));
cmd.Parameters.Add(new OleDbParameter("@typeCode", "KK3000"));
var o = cmd.ExecuteScalar();
}
}
and now it seems to work... a bit strange though...
Upvotes: 0
Reputation: 17600
From MSDN:
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:
So change your query to:
select 'x' from mytable1 where typecode = ?
and EXISTS (select 'x' from mytable2 where (freq=0 OR freq = ?) and mytable1.id=mytable2.pid)
And you have to add parameters in the same order as they occur in query.
Upvotes: 1