CREATE FUNCTION [dbo].[DrugsStagnant]  (@Id numeric(18,0))
RETURNS
@Stagnant TABLE
   (
   WarehouseCode VARCHAR(3),
   DrugCode VARCHAR(15), 
   DrugName nvarchar(100)
   )
AS  
BEGIN 
    INSERT @Stagnant
	SELECT WarehouseCode, DrugCode, DrugName FROM (
	SELECT 
	CASE
	  WHEN Kind_Flag = 1 THEN Sender ELSE Reciver
	END AS WarehouseCode,
	Tmpdrughavaleh.K_Code DrugCode, Kalaid.Name1 DrugName  FROM dbo.TmpDrugHavaleh WITH (NOLOCK)
	INNER JOIN dbo.KalaId WITH (NOLOCK) ON KalaId.K_Code = TmpDrugHavaleh.K_Code
	INNER JOIN Tmpdrugh WITH (NOLOCK) ON TmpDrugH.Id_Havaleh = TmpDrugHavaleh.Id_Havaleh
	WHERE TmpDrugH.Id_Havaleh = @Id  
	) AS T INNER JOIN Anbar WITH (NOLOCK) ON T.WarehouseCode = A_Code AND T.DrugCode = K_Code
	WHERE Active_Flag = 1
RETURN
END