Zach
Zach

Reputation: 30311

SQL query where a column name contains &

I have a SQL Server 2008 database, with a column named ES&D. I want to query based on that column like this:

SELECT ES&D FROM myDB

Or this:

SELECT * FROM myDB WHERE ES&D=1

But I get the following error (I'm using SQL Server Management Studio to write queries):

Msg 207, Level 16, State 1, Line 1
Invalid column name 'ES'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'D'.

Is there any way to escape the & in the column name, such that SQL treats it literally?

Upvotes: 2

Views: 2834

Answers (1)

marc_s
marc_s

Reputation: 754538

Yes - enclose your column name in square brackets:

SELECT [ES&D] FROM myDB

That should work - I hope! Same goes for e.g. table or column names with spaces in them ([Order Details]), or object names that are SQL keywords, like an [Order] table

Upvotes: 8

Related Questions