Question

I have a temp table which is imported into SQL and has column names such as...

Field1, Field2, Field3, Field4, Field5, Field6 and so on.

One record in the table contains the actual column names such as...

fldBP, fldDialysis, fldMed, fldInventory, fldDoctors

I need to loop through or create a basic query to changed each column name to that located in the column and record containing the real name. Is there a simple way of doing this? The record with the column names is always the first one.

Was it helpful?

Solution

Since you already have all the data in sql server no point importing it again, just use something like

SELECT MAX(LEN(Field1)) Field1Len
      ,MAX(LEN(Field2)) Field2Len
      ,MAX(LEN(Field3)) Field3Len
FROM Table_Name

This will give you and approximate idea what length each column needs to be, Create A new Table using the column names from your table where you already have your data, and Delete that row, Then Simply do an Insert Into your new table something like this,,,

INSERT INTO New_Table (fldBP, fldDialysis, fldMed, fldInventory, fldDoctors,....)
SELECT Field1, Field2, Field3, Field4, Field5, Field6,......
FROM Table_Name

/*Finally Drop the stagging\Bad table*/

DROP TABLE Table_Name
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top