我想将数据库从MS Access迁移到SQL Server,我试图修改我的SQL查询。
我有这样的c#代码:
private DataSet GetIncident_ByIncident(string inc_num)
{
MainIncident mi = new MainIncident();
mi.incident_full_number = inc_num;
string query = @"SELECT MainIncidentTable.Incident_Full_Num ,
MainIncidentTable.Customer_Name ,
MainIncidentTable.Service_Representative ,
MainIncidentTable.Incident_Date ,
MainIncidentTable.Average_Invoice ,
MainIncidentTable.Street ,
MainIncidentTable.City ,
MainIncidentTable.Contact ,
IncidentStatuses.Incident_Status_Name,
Stations.Station_Name
FROM(MainIncidentTable INNER JOIN
Stations ON MainIncidentTable.Current_Station_ID = Stations.Station_ID)
INNER JOIN IncidentStatuses ON MainIncidentTable.Current_Incident_Status_Id = IncidentStatuses.Incident_Status_Id
WHERE Incident_Full_Num = '@Incident_Full_Num'";
List<OleDbParameter> l = new List<OleDbParameter>();
l.Add(new OleDbParameter("@Incident_Full_Num", mi.incident_full_number));
l.Add(new OleDbParameter("@Customer_Name", mi.customer_name));
l.Add(new OleDbParameter("@Service_Representative", mi.service_representative));
l.Add(new OleDbParameter("@Incident_Date", mi.incident_date));
l.Add(new OleDbParameter("@Average_Invoice", mi.average_invoice));
l.Add(new OleDbParameter("@Street", mi.street));
l.Add(new OleDbParameter("@City", mi.city));
l.Add(new OleDbParameter("@Contact", mi.contact));
l.Add(new OleDbParameter("@Current_Station_ID", mi.current_station_id));
l.Add(new OleDbParameter("@Current_Incident_Status_Id", mi.current_incident_status_id));
var con = GetDataSetWithParameters(query, l);
return con;
}
连接方式:
public static DataSet GetDataSetWithParameters(string query, List<OleDbParameter> parameters)
{
DataSet ds = new DataSet();
OleDbConnection Con = new OleDbConnection(sqlConnectionString);
Con.Open();
try
{
using (OleDbCommand cmd = new OleDbCommand(query, Con))
{
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
using (OleDbDataAdapter Adapter = new OleDbDataAdapter(cmd))
{
Adapter.Fill(ds);
}
return ds;
}
}
catch
{
throw;
}
finally
{
CloseConnection(ref Con);
}
}
SQL查询正在工作,但不返回行。我猜问题出在查询参数的语法上。
谁能给我指路?参数不能用引号括起来。图书馆会处理的。即使用
WHERE Incident_Full_Num = @Incident_Full_Num
不是
WHERE Incident_Full_Num = '@Incident_Full_Num'
编辑
哦,对不起,忘了,OleDb不使用命名参数,只使用位置参数。看到文档
所以要么更新你的查询到
WHERE Incident_Full_Num = ?
或者用SqlCommand
和SqlParameter
代替OleDbCommand
和OleDbParameter
。
请注意,如果使用OleDbCommand
,传递参数的顺序很重要。即,第一个?
将绑定到第一个参数,第二个?
将绑定到第二个参数,依此类推。如果在查询中需要两次使用相同的参数,则还需要传递两次。
而且似乎只使用第一个参数。为什么要向命令传递大量未使用的参数?