这是我的代码。两者之间的日期有效,但是当我添加LEFT JOIN
时,它会显示错误:
左边的语法错误
cn.Open();
SqlCommand cmd = cn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT FirstName,LastName,Date,Time,Day from
Attendance where Sn=@Sn and ([Date] between @SD and @ED) left JOIN
EmployeeTable ON Attendance.EmployeeID = EmployeeTable.EmployeeID
Order by Attendance.AttendanceID";
cmd.Parameters.Add(new SqlParameter("@Sn", txtSn.Text));
cmd.Parameters.Add(new SqlParameter("@SD", DTPStart.Text));
cmd.Parameters.Add(new SqlParameter("@ED", DTPEnd.Text));
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView2.DataSource = dt;
cn.Close();
答案 0 :(得分:3)
您必须保持SQL语句的顺序。首先是join
,然后是where
- 条款。
变化
SELECT FirstName,LastName,Date,Time,Day from
Attendance where Sn=@Sn and ([Date] between @SD and @ED) left JOIN
EmployeeTable ON Attendance.EmployeeID = EmployeeTable.EmployeeID
Order by Attendance.AttendanceID
为:
SELECT FirstName,LastName,Date,Time,Day from
Attendance left JOIN EmployeeTable ON Attendance.EmployeeID = EmployeeTable.EmployeeID
where Attendance.Sn=@Sn and (Attendance.[Date] between @SD and @ED)
Order by Attendance.AttendanceID
https://technet.microsoft.com/en-us/library/ms190617(v=sql.105).aspx
答案 1 :(得分:0)
这是因为你正在使用联接的地方。它应该在之前和之后,在您处理多个表时尝试使用别名。所以CommandText初始化将如下所示
cmd.CommandText = "SELECT b.FirstName,b.LastName,a.Date,a.Time,a.Day" +
" from Attendance a" +
" left JOIN EmployeeTable b ON a.EmployeeID = b.EmployeeID" +
" where a.Sn=@Sn and (a.[Date] between @SD and @ED)" +
" Order by a.AttendanceID";
答案 2 :(得分:0)
您获得的错误是因为您没有以正确的方式编写查询。 WHERE
条款应始终位于JOIN
语句之后。另外,请确保在JOIN
查询中处理SQL
语句时使用别名,以便更好地理解。
我已编辑了您的代码,您可以将其替换为现有代码:
cn.Open();
SqlCommand cmd = cn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT et.FirstName,et.LastName,at.Date,at.Time,at.Day from
Attendance at left JOIN
EmployeeTable et ON at.EmployeeID = et.EmployeeID
where at.Sn=@Sn and (at.[Date] between @SD and @ED)
Order by Attendance.AttendanceID";
cmd.Parameters.Add(new SqlParameter("@Sn", txtSn.Text));
cmd.Parameters.Add(new SqlParameter("@SD", DTPStart.Text));
cmd.Parameters.Add(new SqlParameter("@ED", DTPEnd.Text));
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView2.DataSource = dt;
cn.Close();