[英]SQL command parameter Must declare variable error
我有一个返回信息的数据表方法,但我的参数有问题,它一直抛出一个必须声明变量'@SUPartnerNo'错误。 我试图谷歌,但我找到的解决方案都没有帮助。 我不想将我的参数直接嵌入到我的查询中,因为它不是很好的做法
public DataTable SearchInvoiceHeader(string SUPartnerNo, string invoiceNo, string bdate, string edate)
{
DataTable dt = new DataTable();
try
{
StringBuilder mySelectQuery = new StringBuilder(9000);
mySelectQuery.AppendLine(@"SELECT I.[InvoiceNo]
,I.[SUPartnerNo]
,I.[OrderNo]
,I.[RefNo]
,I.[DocType]
,I.[SAP_Type]
,I.[SUName]
,I.[InvoiceDate]
,I.[PaymentDate]
,I.[BaseLineDate]
,I.[DeliveryDate]
,I.[DeliveryNoteNo]
,I.[TotalAmount]
,I.[StartTime]
,p.ProcessType
,s.DocDate
,s.IDocNo
,s.TotalValue
FROM [dbo].[mainhead] I WITH (NOLOCK)
LEFT JOIN [INV_Processed] p WITH (NOLOCK)
ON p.InvoiceNo = I.InvoiceNo
AND p.PartnerNo = I.SUPartnerNo
LEFT JOIN dbo.INV_SAP s WITH (NOLOCK)
ON s.InvoiceNo = I.InvoiceNo
AND s.SupplierNo = I.SUPartnerNo
WHERE
(I.SUPartnerNo =@SUPartnerNo) OR (I.InvoiceNo = @InvoiceNo)
and I.[StartTime] between @bdate and @edate");
SqlConnection myConnection;
myConnection = new SqlConnection(ConnectionString);
SqlCommand myCommand = new SqlCommand(mySelectQuery.ToString());
myCommand.Parameters.AddWithValue("@SUPartnerNo", SUPartnerNo);
myCommand.Parameters.AddWithValue("@InvoiceNo", invoiceNo);
myCommand.Parameters.AddWithValue("@bdate", bdate);
myCommand.Parameters.AddWithValue("@edate", edate);
myCommand.Connection = myConnection;
myConnection.Open();
SqlDataAdapter mytable = new SqlDataAdapter(mySelectQuery.ToString(), myConnection);
myCommand.ExecuteNonQuery();
mytable.Fill(dt);
myConnection.Close();
您正在将参数添加到错误的命令。 Fill
方法不使用您创建的myCommand
对象。 将参数添加到SqlDataAdapter
:
mytable.SelectCommand.Parameters.AddWithValue(...)
您可以从代码中省略与myCommand
相关的任何内容,包括ExecuteNonQuery()
调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.