﻿DROP PROCEDURE IF EXISTS uspGetAllAlkalmazottByIntezmeny
GO

CREATE PROCEDURE uspGetAllAlkalmazottByIntezmeny
   @pIntezmenyId INT
  ,@pTanevId INT = NULL
AS
BEGIN
  SET NOCOUNT ON;

  DECLARE @sql NVARCHAR(MAX)

  SET @sql = N'
  SELECT
     a.C_NYOMTATASINEV AS Nev
    ,a.C_OKTATASIAZONOSITO AS OktatasiAzonosito
    ,a.C_IDPEGYEDIAZONOSITO AS IdpEgyediAzonosito
  FROM
  (
    SELECT 
       f.C_NYOMTATASINEV
      ,f.C_OKTATASIAZONOSITO
      ,f.C_IDPEGYEDIAZONOSITO
      ,IIF(f.C_NEVSORREND = ''T'', f.C_UTONEV + '' '' + f.C_VEZETEKNEV, f.C_VEZETEKNEV + '' '' + f.C_UTONEV) AS NevElotagNelkul'
  IF @pTanevId IS NULL
  BEGIN
    SET @sql += N'
      ,ROW_NUMBER() OVER(PARTITION BY f.C_IDPEGYEDIAZONOSITO, f.C_VEZETEKNEV, f.C_UTONEV ORDER BY IIF(f.C_NEVSORREND = ''T'', f.C_UTONEV + '' '' + f.C_VEZETEKNEV, f.C_VEZETEKNEV + '' '' + f.C_UTONEV), f.C_IDPEGYEDIAZONOSITO, tv.C_SORSZAM DESC) as Rn'
  END

  SET @sql += N'
    FROM T_ALKALMAZOTT_OSSZES a
      INNER JOIN T_FELHASZNALO_OSSZES f ON f.ID = a.ID AND f.TOROLT = ''F''
      INNER JOIN T_INTEZMENY_OSSZES i ON i.ID = a.C_ALINTEZMENYID AND i.TOROLT = ''F''
      INNER JOIN T_TANEV_OSSZES tv ON tv.ID = a.C_ALTANEVID AND tv.TOROLT = ''F''
    WHERE a.C_ALINTEZMENYID = @intezmenyId'

  IF @pTanevId IS NOT NULL
  BEGIN
    SET @sql += N'
      AND a.C_ALTANEVID = @tanevId'
  END

  SET @sql += N'
      AND a.TOROLT = ''F''
  ) AS a'

  IF @pTanevId IS NULL
  BEGIN
    SET @sql += N'
  WHERE a.Rn = 1'
  END

  SET @sql += N'
  ORDER BY a.NevElotagNelkul'

  --print @sql
  EXEC sp_executesql @sql
    ,N'@intezmenyId INT
      ,@tanevId INT = NULL'
    ,@pIntezmenyId
    ,@pTanevId

END
GO

