我有一个约会表单,它将根据约会表格在gridview中显示数据。我编写了select语句,以便PatientID将更改为患者表中的pFirstName,并且mcID将更改为medicalcentre表中的mcCentre。有一个WHERE查询,因为我只想显示只属于当前用户登录的约会/行。当我调试我得到这个错误不明确的列名称patientID。
我的预约表格
我的3张预约表,医疗中心和患者。
我的查看约会表单代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class member_viewappointment : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
// call BindGridView
bindGridView();
}
}
private void bindGridView()
{
int ID = Convert.ToInt32(Session["ID"].ToString());
//get connection string from web.config
string strConnectionString = ConfigurationManager.ConnectionStrings["sacpConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT aStatus, aDate, aTime, aContact, aHeight, aWeight, med.mcCentre, pat.pFirstName from appointment AS app ";
strCommandText += " LEFT OUTER JOIN MEDICALCENTRE as med on app.appointmentid = med.mcid";
strCommandText += " LEFT OUTER JOIN PATIENT as pat on app.patientid = pat.patientid ";
strCommandText += " WHERE patientid = " + ID.ToString();
try
{
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
grdViewAppointment.DataSource = dt;
grdViewAppointment.DataBind();
lblResult.Text = "";
reader.Close();
}
catch (SqlException ex)
{
lblResult.Text = "Error:" + ex.Message.ToString();
}
finally
{
myConnect.Close();
}
}
}
答案 0 :(得分:4)
问题:两个表格中都有patientid
列(appointment
和MEDICALCENTRE
)。所以当您单独使用列名patientid
时,如果没有提及它所属的表名,它就无法识别并导致一种暧昧的情况。
解决方案,因此您应该在列名patientid
之前提及表名或表别名,以消除patientid
所属的表格的歧义。
替换它:
strCommandText += " WHERE patientid = " + ID.ToString();
有了这个:
strCommandText += " WHERE app.patientid = " + ID.ToString();
建议:您的SELECT
查询对SQL Injection Attacks
开放,因此我建议您使用Parameterised queries
来避免这些问题。
使用参数化查询:
strCommandText += " WHERE patientid = @patientid";
try
{
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValue("@patientid",ID.ToString());
/*remaining same*/
}