不明确的列名?

时间:2015-01-13 18:09:05

标签: c# asp.net sql-server

好的..我无法找到问题,所以我在这里发帖。附:我是MSSQL的新手,所以请温柔xD

我收到了歧义栏名称"名称"

我有两张桌子:Cardiology和Cardio_Schedule。我想从两者中选择一些列并在gridview中显示它们。我已经提出了一个问题..这就是它:

string str = @"
SELECT Cardiology.CID,
       Cardiology.Name,
       Cardiology.Designation,
       Cardiology.Qualification,
       Cardiology.Shift,
       Cardiology.Appointment_Timings,
       Cardio_schedule.Ward_rounds,
       Cardio_schedule.Slot1,
       Cardio_schedule.Slot2,
       Cardio_schedule.Slot3,
       Cardio_schedule.Slot4,
       Cardio_schedule.BreakTime,
       Cardio_schedule.Slot5,
       Cardio_schedule.Slot6,
       Cardio_schedule.Slot7,
       Cardio_schedule.Slot8
FROM   Cardiology
       CROSS JOIN Cardio_schedule
WHERE  Cardiology.Name = Cardio_schedule.Name
       AND Name = '" + TextBox1.Text + "'";
            cmd = new SqlCommand(str, con);
            con.Open();
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
            con.Close();

IDK问题是什么。 我确实用ON尝试过,但后来在'' ON'附近说错误的语法。任何形式的帮助将不胜感激。 谢谢!

3 个答案:

答案 0 :(得分:5)

您的问题出在过滤器中: -

AND Name = '" + TextBox1.Text + "'";
            cmd = new SqlCommand(str, con);

根据您想要参考的表格进行更改: -

AND Cardiology.Name = '" + TextBox1.Text + "'";
            cmd = new SqlCommand(str, con);

请注意您的查询已针对SQL Injection attack打开,因此您应该使用参数化查询,而不是这样: -

string str = "Cardiology.CID,Cardiology.Name, .....WHERE  
              Cardiology.Name = Cardio_schedule.Name
              AND Cardiology.Name = @Name";
cmd = new SqlCommand(str, con);
cmd.Parameters.Add("@Name",DbType.NVarChar,20).Value = TextBox1.Text;
.....and so on

请注意,我已将您的数据类型视为NVarchar(20),您需要相应更改。

答案 1 :(得分:2)

你最后错过了。

SELECT Cardiology.CID,
       Cardiology.NAME,
       Cardiology.Designation,
       Cardiology.Qualification,
       Cardiology.Shift,
       Cardiology.Appointment_Timings,
       Cardio_schedule.Ward_rounds,
       Cardio_schedule.Slot1,
       Cardio_schedule.Slot2,
       Cardio_schedule.Slot3,
       Cardio_schedule.Slot4,
       Cardio_schedule.BreakTime,
       Cardio_schedule.Slot5,
       Cardio_schedule.Slot6,
       Cardio_schedule.Slot7,
       Cardio_schedule.Slot8
FROM   Cardiology
       CROSS JOIN Cardio_schedule
WHERE  Cardiology.NAME = Cardio_schedule.NAME
       AND Cardiology.NAME = 'as'  -- `Cardiology` alias Missed

答案 2 :(得分:0)

在查询结束时应该有:

WHERE Cardiology.Name = Cardio_schedule.Name AND Cardio_schedule.Name = '"

WHERE Cardiology.Name = Cardio_schedule.Name AND Cardiology.Name = '"

只编写Name属性会使其不明确。