Working With Bad SQL Column Names (Even If It's Your Fault)
Posted By : todd sharp Posted At : December 4, 2006 9:32 AM Posted In: SQL
7
It must be SQL day at cfsilence. This is really obvious stuff, but even supreme coders like myself make mistakes now and then (and if you really think I believe that I am a supreme coder, I have some land in Florida I'd like to sell you). I just pulled an Excel file into my SQL Server 2000 database at work to use as a temp table to update an existing table with a new 'rank' for 2007. Well, it just so happened that the rank column was named '2007_mw_rank' - not the best column name, but it was there so I went with it since it was only a temp table. Apparently column names in SQL Server can not begin with a number (as I said, I normally wouldn't have done it). So when I went to query the table with the following query:
FROM temp_2007_priority
WHERE 2007_mw_rank IS NULL
I received the following error:
Line 3: Incorrect syntax near '_mw_rank'.
Like all poorly named columns, surrounding the column name with [] was a temp fix:
FROM temp_2007_priority
WHERE [2007_mw_rank] IS NULL
But the best solution would have been to rename the column so that it did not begin with a number at all!



Access uses brackets like SQL Server: [my column name]
MySQL uses ticks: `my column name`
Oracle uses quotes: "my column name"
PostGreSQL uses quotes: "my column name"
Regards, Aislin
Regards,
Angela
A customer sent me an MDB that he wanted loaded into MSSQL. Seemed simple enough until my direct link broke so I had to program it. Still seemed to be a piece of cake. Just select all the data from the access db and insert it into the MSSQL db. But when I tried
INSERT INTO newtable
(COL1,COL2)
VALUES
('[stupid name 1]','[stupid name 2]')
It did not work.
After pounding my head against the monitor I realized he didn't need the mdb returned and I had total control of it. Stoopid me. DOH *slap in the head*
But I may play around and figure out why it isn't working.
The escapes are for the table and field names, not the values.
So, you would want:
INSERT INTO newtable
([COL1],[COL2])
VALUES
('stupid name 1','stupid name 2')
If you are using SELECT INTO, then you don't want a VALUES clause in your insert statement.