我有3个表,我从(ModuleStaff
,Staff
,Roles
检索。我打算做的是在一行中的gridview中显示数据。例如,负责组号1和2的staff(adrian)
将显示为:
StaffName | RoleName | GroupNumber
Adrian | Lecturer | 1,2
目前,我遇到的问题是同一个staff(adrian)
,但使用不同的角色名称,即使其数据库数据对于导师和领导者空白
我现在得到了什么:
groupnumbers (1 and 2)
应该是什么:
StaffName | RoleName | GroupNumber
Adrian | Lecturer | 1,2
Adrian | Tutor | 1,2
Adrian | Leader | 1,2
这是我的代码:
StaffName | RoleName | GroupNumber
Adrian | Lecturer | 1,2
Adrian | Tutor |
Adrian | Leader |
我不太清楚我应该如何查询XML Path / sql语句,以便根据public DataTable DisplayModuleStaffGroup(string year, string module, string diploma)
{
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MARSConnectionString"].ConnectionString))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT ms.ModuleCode, ms.ModuleYear, ms.DiplomaID, sr.RoleName, s.StaffName, s.StaffStatus, GroupNumber = ";
cmd.CommandText += " substring((SELECT ( ', ' + GroupNumber ) FROM ModuleStaff ms2, Staff s2 ";
cmd.CommandText += " WHERE ms.StaffID = ms2.StaffID AND ms2.StaffID = s2.StaffID ";
cmd.CommandText += " ORDER BY s2.StaffName, ms2.GroupNumber ";
cmd.CommandText += " FOR XML PATH( '' )), 3, 1000) ";
cmd.CommandText += " FROM ModuleStaff ms ";
cmd.CommandText += " INNER JOIN StaffRoles sr ON ms.RoleID = sr.RoleID ";
cmd.CommandText += " INNER JOIN Diploma d ON ms.DiplomaID = d.DiplomaID ";
cmd.CommandText += " INNER JOIN Staff s ON ms.StaffID = s.StaffID ";
cmd.CommandText += " WHERE (ms.DiplomaID = @dip) AND (ms.ModuleYear = @year) AND (ms.ModuleCode = @code) ";
cmd.CommandText += " ORDER BY ms.RoleID DESC ";
cmd.Parameters.AddWithValue("@dip", diploma);
cmd.Parameters.AddWithValue("@year", year);
cmd.Parameters.AddWithValue("@code", module);
DataSet dSet = new DataSet();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dSet, "DisplayModuleStaffGroup");
return dSet.Tables["DisplayModuleStaffGroup"];
}
}
}
}
catch
{
throw;
}
finally
{
}
}
和rolename
为我提供组号。谁可以帮我这个事?谢谢。
答案 0 :(得分:0)
你可以在sql中完成循环.. 这是你可以申请的想法
declare @totalStaff int
declare @totalRoles int
declare @staffCount int
declare @roleCount int
declare @staffId int
declare @staffName varchar(max)
declare @roleId int
declare @roleName varchar(max)
declare @groupCount int
declare @table table(staffName varchar(max),roleName varchar(max),roles varchar(max))
set @staffCount=1
set @roleCount=1
set @totalStaff=(select count(*) from staff)
while(@staffCount<=@totalStaff)
begin
set @staffId=select a.ID from
(select row_number() over(order by ID) as sr,ID from satff)a
where a.sr=@staffCount
set @staffName=(select staffName from staff where staffId=@staffId)
set @totalRoles=(select count(*) from roles where staffId=@staffId)
while(@roleCount<=@totalRoles)
begin
set @roleId=select a.ID from
(select row_number() over(order by ID) as sr,ID from roles)a
where a.sr=@roleCount
set @roleName=(select roleName from roles where roleId=@roleId)
--now same as above go through the loop for group
end
end