CREATE OR ALTER PROCEDURE [HM].[DP_KatPodatkowa_Update]
	@DkId [int],
    @NpId [int],
    @ZeroId [int]
AS
BEGIN
	IF @NpId <> 0
	BEGIN
		UPDATE DP SET katPodatkowa = @NpId
		FROM HM.DP 
		INNER JOIN HM.XT ON xt.super = 10000 AND XT.id = DP.stvat AND XT.subtyp = 7
		where DP.super = @DkId
	END
	IF @ZeroId <> 0
	BEGIN
		WITH 
		NpRateId([Value]) AS (
			SELECT TOP (1) Id
			FROM HM.XT
			WHERE super = 10000
				AND subtyp = 7
				AND flag & 0x200 <> 0
			),
		ZeroRateId([Value]) AS (
			SELECT TOP (1) Id
			FROM HM.XT
			WHERE super = 10000
				AND subtyp = 3
		)
        UPDATE DP SET katPodatkowa = @ZeroId
        FROM HM.DP
        CROSS JOIN NpRateId
        CROSS JOIN ZeroRateId
        INNER JOIN HM.DK ON dk.id = DP.super
        INNER JOIN HM.XT ON xt.super = 10000 AND XT.id = IIF(DK.subtyp = 46, IIF(DP.stvat = NpRateId.Value, NpRateId.Value, ZeroRateId.Value), DP.stvat) AND XT.subtyp = 3
        WHERE DP.super = @DkId
	END
END