When doing INSERT INTO FROM SELECT
you MUST match order of columns in SELECT
statement as they are in INSERT
statement.
Now on other hand you not required to match column order in INSERT
statement to what is in CREATE TABLE
.
It is always recommended to specify COLUMN
in INSERT
statement. Otherwise you assuming that what you selecting matches column order in table that you are inserting into.
In your case you should modify your query like so.
INSERT INTO @T1 (MRN, Encounter)
SELECT
A.Med_Rec_No
, A.[VISIT ID]
, ...
, ...
, ...
)
FROM (
SELECT DISTINCT PAV.PTNO_NUM AS [VISIT ID]
, PAV.Med_Rec_No
, ...
, ...
, ...
)
as alternative you can modify order of column in INSERT
clause
INSERT INTO @T1 (Encounter,MRN)
SELECT
A.[VISIT ID]
,A.Med_Rec_No
, ...
, ...
, ...
)
FROM (
SELECT DISTINCT PAV.PTNO_NUM AS [VISIT ID]
, PAV.Med_Rec_No
, ...
, ...
, ...
)