CREATE PROCEDURE [dbo].[PDSTMTOPYVALEMPSAVEMDEXIST] ( @Variant VARCHAR(20), @StartDate VARCHAR(20), @EndDate VARCHAR(20), @EmployeeIDStart VARCHAR(20), @EmployeeIDEnd VARCHAR(20) ) AS --DECLARE @EmployeeIDStart VARCHAR(20) = '10000087' --DECLARE @EmployeeIDEnd VARCHAR(20) = '10000087' --DECLARE @StartDate VARCHAR(20) = '20200801' --DECLARE @EndDate VARCHAR(20) = '20200831' --DECLARE @Variant VARCHAR(20) = '0001' DECLARE @EmpIDMin VARCHAR(20) = CASE WHEN @EmployeeIDStart <> '' THEN @EmployeeIDStart ELSE '00000000' END DECLARE @EmpIDMax VARCHAR(20) = CASE WHEN @EmployeeIDEnd <> '' THEN @EmployeeIDEnd ELSE '999999999' END DECLARE @Flag VARCHAR(20) DECLARE @EmpIDRun VARCHAR(250) SELECT TOP(1) @EmpIDRun = (tr800.EmployeeID + '-' + pa01.FullName) , @Flag = (CASE WHEN (tr800.Payroll = '1' AND tr800.TM = '') THEN 'PY' WHEN (tr800.Payroll = '' AND tr800.TM <> '') THEN 'TM' WHEN (tr800.Payroll = '1' AND tr800.TM <> '') THEN 'PYTM' END) FROM dbo.PHRPYTR0800 AS tr800 LEFT JOIN dbo.PHRPA0001 AS pa01 ON pa01.EmployeeID = tr800.EmployeeID AND pa01.StartDate <= @EndDate AND pa01.EndDate >= @EndDate WHERE (@StartDate BETWEEN tr800.StartDate AND tr800.EndDate) AND (tr800.EmployeeID BETWEEN @EmpIDMin AND @EmpIDMax) SELECT ISNULL(@EmpIDRun,'') AS EmpIDRun, @Flag AS Flag