尝试将参数从C#传递给OleDbCommand / Connection时,“必须声明标量变量”

时间:2014-01-03 20:11:08

标签: c# sql-server

我第一次尝试将参数与我的查询一起使用,并且我一直收到此错误

  

System.Data.dll中发生未处理的“System.Data.OleDb.OleDbException”类型异常   附加信息:必须声明标量变量“@ SampleID0”。

我从未使用过参数,而是试图弄清楚它们。我相信说dbcmd.Parameters.AddWithValue(...)的部分应该是将值与参数一起添加到命令中,还有其他方法我应该“声明标量变量吗?” listItems可能会有数千个条目,所以如果有更有效的方法可以做到这一点,我会全力以赴。

OleDbConnection dbconn = new OleDbConnection();
OleDbCommand dbcmd = new OleDbCommand();
dbconn.ConnectionString = connectionString;

string[] listItems = new string[2];
listItems[0] = "P00000000683634820055041";
listItems[1] = "P00000000683063257726977";

var parameters = new string[listItems.Length];
for (int i = 0; i < listItems.Length; i++)
{
    parameters[i] = string.Format("@SampleID{0}", i);
    dbcmd.Parameters.AddWithValue(parameters[i], listItems[i]); 
}

dbcmd.CommandText = string.Format("select Analysis.SampleID, Analysis.SampleDateTime, AnalysisResult.ParameterName, AnalysisResult.Slope, AnalysisResult.Bias, " +
"AnalysisResult.ResultValue, AnalysisResult.CalibrationFileName FROM Analysis INNER JOIN AnalysisResult ON (Analysis.AnalysisGUID = AnalysisResult.AnalysisGUID) " +
"where Analysis.SampleID IN ({0})", string.Join(", ", parameters));

dbcmd.Connection = dbconn;
dba = new OleDbDataAdapter(dbcmd);
dba.Fill(dt);
dataGridView1.DataSource = dt;

产生的dbcmd.CommandText:

select Analysis.SampleID, Analysis.SampleDateTime, AnalysisResult.ParameterName, AnalysisResult.Slope, AnalysisResult.Bias, AnalysisResult.ResultValue, AnalysisResult.CalibrationFileName 
FROM Analysis 
INNER JOIN AnalysisResult ON Analysis.AnalysisGUID = AnalysisResult.AnalysisGUID
where Analysis.SampleID IN (@SampleID0, @SampleID1)

2 个答案:

答案 0 :(得分:0)

不要提供几个不同参数的列表,而是尝试传递包含所有参数的单个参数,例如this question

dbcmd.Parameters.AddWithValue(“SampleIDs”,String.Join(“,”,listItems.ToArray()))

然后更改查询:

dbcmd.CommandText =“select Analysis.SampleID,Analysis.SampleDateTime,AnalysisResult.ParameterName,AnalysisResult.Slope,AnalysisResult.Bias,”+                             “AnalysisResult.ResultValue,AnalysisResult.CalibrationFileName FROM Analysis INNER JOIN AnalysisResult ON(Analysis.AnalysisGUID = AnalysisResult.AnalysisGUID)”+                             “其中Analysis.SampleID IN(@SampleIDs)”;

编辑:

正如评论中所指出的,这可能不起作用,但我没有一个OleDB来测试(或者SQL方便的第二个)。但是,由于它被标记为SQL Server,如果是这样,您可以查看Table Value Parameters

答案 1 :(得分:0)

如果您使用@

,则应在参数名称中将?更改为OleDbConnection

parameters[i] = string.Format("?SampleID{0}", i);