I have a query in which I create a table and then insert data into it. My question is this, I have one column where I need to make the data distinct, my output seems to be working correctly but I would like clarification on if this is an acceptable practice.
Here is what my query looks like:
DECLARE @T1 TABLE(
MRN VARCHAR(20)
, [ENCOUNTER] VARCHAR(200)
, ...
, ...
, ...
)
INSERT INTO @T1
SELECT
A.Med_Rec_No
, A.[VISIT ID]
, ...
, ...
, ...
)
FROM (
SELECT DISTINCT PAV.PTNO_NUM AS [VISIT ID] -- MUST I CHANGE THE ORDER?
, PAV.Med_Rec_No -- MUST I CHANGE THE ORDER?
, ...
, ...
, ...
)
Does the INSERT INTO @T1 SELECT
take care of the ordering for me, meaning does it really matter what order I SELECT
items in the FROM
statement as long as my INSESRT INTO
matches what my DECLARE @T1 TABLE
says?
Thank you,
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
, ...
, ...
, ...
)