为什么我的存储过程不适用于所有记录

时间:2016-01-21 08:55:54

标签: sql sql-server tsql stored-procedures

我写了一个商店程序,可以为他的 CURRENT 工作或 INITIAL JOB 选择员工数据,或者两者存在,然后只为< strong> CURRENT 但我只为单个员工实现了这一目标。我无法弄清楚如何为表中的大量员工选择它,因为每个员工可以有CURRENT或INITIAL或BOTH。

ALTER PROCEDURE [dbo].[ReportEmployeeProfile] 0
AS
BEGIN

    SELECT
        PersonalInfo.pk_PersonalInfo_ID,
        PersonalInfo.PersonalInfoReligion,
        PersonalInfo.PersonalInfoPhoneResidence,
        PersonalInfo.PersonalInfoPhoneoffice,
        PersonalInfo.PersonalInfoNIC,
        PersonalInfo.PersonalInfoName,
        PersonalInfo.PersonalInfoMobile,
        PersonalInfo.PersonalInfoMaritalStatus,
        PersonalInfo.PersonalInfoGender,
        PersonalInfo.PersonalInfoFatherHusbandName,
        CONVERT(varchar, PersonalInfo.PersonalInfoEntryDateTime, 106),
        PersonalInfo.PersonalInfoEmailAddress,
        PersonalInfo.PersonalInfoDomicile,
        CONVERT(varchar, PersonalInfo.PersonalInfoDOB, 106) AS PersonalInfoDOB,
        PersonalInfo.PersonalInfoComputerLiterate,
        PersonalInfo.PersonalInfoAddress,
        PersonalInfo.fk_WebUsers_PersonalInfo_UserID,
        PersonalInfoEmployeePicture,
        ServiceInfo.ServiceInfoInitialBPS,
        ServiceInfo.ServiceInfoInitialDesignation
    FROM PersonalInfo
    INNER JOIN ServiceInfo
        ON ServiceInfo.fk_PersonalInfo_ServiceInfo_PID = PersonalInfo.pk_PersonalInfo_ID
    WHERE ServiceInfo.ServiceInfoJobStatus = ?

更新 JobStatuses:     1 =初始     2 =先前     3 =当前

1 个答案:

答案 0 :(得分:0)

也许window function会帮助您解决任务。看一下这个SQL代码。我已经使用ROW_NUMBER()函数来计算员工的所有工作状态并采取最后一次。

 SELECT T.* FROM
     (SELECT
            P.pk_PersonalInfo_ID, 
            P.PersonalInfoReligion, 
            P.PersonalInfoPhoneResidence,
            P.PersonalInfoPhoneoffice, 
            P.PersonalInfoNIC, 
            P.PersonalInfoName, 
            P.PersonalInfoMobile, 
            P.PersonalInfoMaritalStatus, 
            P.PersonalInfoGender, 
            P.PersonalInfoFatherHusbandName, 
            Convert(varchar, P.PersonalInfoEntryDateTime, 106) AS PersonalInfoEntryDateTime, 
            P.PersonalInfoEmailAddress,
            P.PersonalInfoDomicile, 
            Convert(varchar,P.PersonalInfoDOB, 106) as PersonalInfoDOB, 
            P.PersonalInfoComputerLiterate, 
            P.PersonalInfoAddress,
            P.fk_WebUsers_PersonalInfo_UserID, 
            PersonalInfoEmployeePicture, 
            SI.ServiceInfoInitialBPS, 
            SI.ServiceInfoInitialDesignation,
            ROW_NUMBER() OVER(PARTITION BY P.pk_personalInfo_ID ORDER BY SI.ServiceInfoJobStatus DESC) AS row_num
     From PersonalInfo AS P
         JOIN ServiceInfo AS SI ON SI.fk_PersonalInfo_ServiceInfo_PID= P.pk_PersonalInfo_ID) AS T
 WHERE T.row_num = 1