tags:

views:

367

answers:

2

I need a table that stores key-value pairs, so I created one with a column called "Key" and a column called "Value".

This fails:

insert into mykeyvalues (Key,Value) values ('FooKey', 'FooValue')

"Incorrect syntax near the keyword 'key'."

Maybe I shouldn't call it "Key", but I just wonder if it is possible to work with a column who's name is a sql keyword?

Thanks

+5  A: 

You can surround column names like that with [ ] brackets. Therefore:

insert into mykeyvalues ([Key],[Value]) values ('FooKey', 'FooValue')
John Christensen
Thanks for your answer!
Kurt
+6  A: 

Use either backticks (`) or double quotes (") around the identifiers in your query. For example:

INSERT INTO mykeyvalues ("Key", "Value") values ('FooKey', 'FooValue')

But in the long-run, this just reduces portability. It's easier to use a different name.

James Skidmore
Actually, I believe that your example is ANSI SQL standard-conformant.
RBarryYoung
Yes, but real-life DBs often don't respect ANSI -- e.g. one wants double quotes, another one wants brackets, yet another wants backticks, etc, etc -- one headache after the other:-(
Alex Martelli
Thanks. I'm not sure whether John's answer or this one should be the accepted answer. Both works like a charm.
Kurt
this one should be the correct answer, it's T-SQL and not only MS-SQL, so it will work with almost all SQL queries and not only queries running on Microsoft SQL Server...
balexandre
It assumes SET QUOTED IDENTIFIER ON for MS SQL. ANSI or not, using " is confusing and hard for readability if you only us MS SQL.
gbn