USE [Arizona]
DECLARE @phidx VARCHAR(7) = '1065852';

/*
--to find a phidx with several subs:
SELECT TOP 1000
    [ITK_key], COUNT(1) AS cnt
FROM [dbo].[Item_key] [ik]
WHERE [ik].[ITK_type] = 1 --phcode
AND EXISTS(
    SELECT 1
    FROM [dbo].[PHGD_ACSC] [pa]
    WHERE [pa].[PHGD_ACSC_PharmacodeNum] = [ik].[ITK_key]
)
AND EXISTS(
    SELECT 1
    FROM [dbo].[PHGD_ACXI] [pa2]
    WHERE [pa2].[PHGD_ACXI_PharmacodeNum] = [ik].[ITK_key]
)
GROUP BY [ik].[ITK_key]
HAVING COUNT(1)>1
ORDER BY [ik].[ITK_key] DESC 
;
*/

SELECT *
FROM [dbo].[PHGD_ACSC] [pa]
WHERE [pa].[PHGD_ACSC_PharmacodeNum]=@phidx

SELECT *
FROM [dbo].[PHGD_ACXI] [pa]
WHERE [pa].[PHGD_ACXI_PharmacodeNum]=@phidx

SELECT 
      [i].[Item_ID]
    ,[it].[ITTX_description]
    ,[it].[ITTX_language]
    ,[ik].[Item_key_ID]
    ,[ik].[ITK_key]
    ,[ik].[ITK_label_text]
    ,[ik].[ITK_subsidiary]
    ,[pi].*
FROM [dbo].[Item] [i]
    JOIN [dbo].[Item_key] [ik] ON ik.[ITK_item] = i.[Item_ID]
    JOIN [dbo].[PH_item] [pi] ON [pi].[PHIT_item] = i.[Item_ID]
    LEFT JOIN [dbo].[Item_text] [it] ON it.[ITTX_item] = i.[Item_ID] AND [it].[ITTX_language] = 1
WHERE [ik].[ITK_type] = 1 --phcode
AND [ik].[ITK_key]=@phidx
ORDER BY [ik].[ITK_key]
;

return
SELECT 
      [i].[Item_ID]
    ,[it].[ITTX_description]
    ,[it].[ITTX_language]
    ,[ik].[Item_key_ID]
    ,[ik].[ITK_key]
    ,[ik].[ITK_label_text]
    ,[ik].[ITK_subsidiary]
    ,[pi].*
FROM [dbo].[Item] [i]
    JOIN [dbo].[Item_key] [ik] ON ik.[ITK_item] = i.[Item_ID]
    JOIN [dbo].[PH_item] [pi] ON [pi].[PHIT_item] = i.[Item_ID]
    LEFT JOIN [dbo].[Item_text] [it] ON it.[ITTX_item] = i.[Item_ID] AND [it].[ITTX_language] = 1
WHERE [ik].[ITK_type] = 1 --phcode
ORDER BY [ik].[ITK_key]
;
