CREATE OR ALTER PROCEDURE dbo.sp_StokDepoDurumu
(
    @StokKodu      nvarchar(40) = NULL,
    @Depo          nvarchar(30) = NULL,
    @FaturaTarihi  smalldatetime = NULL
)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        SH.Depo,
        SH.StokKodu,

        ISNULL(SUM(CASE 
            WHEN SH.GC = 'G' THEN SH.Miktar
            WHEN SH.GC = 'C' THEN -SH.Miktar
            ELSE 0
        END), 0) AS Bakiye

    FROM dbo.STOKHAR AS SH,
	STOKKARTI SK 
    WHERE SH.StokKodu = SK.Kodu
	AND SK.AktifPasif = 'A'
	AND SH.FisTuru <> 'Ý'
    AND (NULLIF(@StokKodu,'') IS NULL OR SH.StokKodu = @StokKodu)
    AND (NULLIF(@Depo,'') IS NULL OR SH.Depo = @Depo)
    AND (NULLIF(@FaturaTarihi,'') IS NULL 
            OR SH.FaturaTarihi <= @FaturaTarihi)
    GROUP BY
        SH.Depo,
        SH.StokKodu
    ORDER BY
        SH.Depo,
        SH.StokKodu;
END