See my code
DECLARE @MAXCOUNT INT;
IF OBJECT_ID('tempdb..#VST_DIA') IS NOT NULL
DROP TABLE #VST_DIA
SELECT
vst_int_id,
icd9_code_fmt
--present_at_admit_fg
INTO
#VST_DIA
FROM
TPM318_VISIT_DIAGNOSIS VST_DIA (NOLOCK)
INNER JOIN TSM910_ICD9_REF ICD (NOLOCK)
ON ICD.icd9_int_id = VST_DIA.icd9_int_id
--INNER JOIN TPM300_PAT_VISIT VST (NOLOCK)
--ON VST.vst_int_id = VST_DIA.vst_int_id
WHERE
1=1
AND...