如何使用存储过程从不同的表中检索数据?

时间:2012-07-17 08:06:03

标签: sql-server-2008 stored-procedures

大家好我有四张桌子三张桌子有主键,第四张桌子有三张foriegn键..现在我想写一个选择程序

my tables look like this

          usertable                                       RoleTable
  -----------------------                        ---------------------------
   UserID|UserName|userEmail|Pwd|RoleID                RoleID|RoleName
     1   |Anil    |akanil@gma|123|1                       1   |Admin


       Projecttable                                    WorkAssignedTable
-----------------------                       ---------------------------
ProjectID|ProName|                                  WorkID|userId|ProjectID|RoleID
     1   |Anil                                            |

现在我想为workassigned表编写一个select store过程,我必须得到它 来自sertbale的[UserName],[UserMailId],来自角色tbale的[rolename],来自Projecttable的[ProjectName]可以为如何编写商店的任何一个帮助提供此过程

2 个答案:

答案 0 :(得分:1)

使用此查询

    Select U.UserName, R.RoleName,P.ProName from WorkAssignedTable WA 
inner join usertable U on WA.UserID = U.UserID
inner join RoleTable R on WA.RoleID = R.RoleID
inner join Projecttable P on WA.ProjectID = P.ProjectID

您可以使用左外连接(如果需要WorkAssignedTable的整个记录​​)

答案 1 :(得分:0)

我最终这样做了:

    select  WorkAssigned.WorkID, usertable.EmployeeName, usertable.EmployeeEmailId,RoleTable.EmplopyeeRole,Projects.projectName,WorkAssigned.[Status] from WorkAssigned  
inner join EmployeeGroup  on RoleTable.GroupId=WorkAssigned.GroupId
inner join Projects  on Projects.ProjectId=WorkAssigned.ProjectId 
inner join EmployeeDetails on  usertable.EmployeId=WorkAssigned.EmployeId