views:

46

answers:

2

Square brackets allow you to use names for columns or aliases that contain characters not permitted for column names or aliases.

a) I’ve noticed that lots of times table and column names are enclosed inside square brackets, even though their names consist of perfectly legal characters. Why is that?

b) As far as I know, square brackets enclosing object’s name aren’t actually a part of that name. Thus, if we create a table named [A]:

CREATE TABLE [A] ( … )

we can later reference it without using brackets:

SELECT * FROM A

But why isn’t the same true when I try to reference a column KEY from a table returned by CONTAINSTABLE function? Namely, if I omit the brackets enclosing column name, I get an error:

SELECT ct.KEY   
FROM CONTAINSTABLE(fullText,*,'some_string') as ct

thanx

+1  A: 

KEY is a reserved word in SQL so requires the brackets to use it as a column name.

I think lots of the time you see superfluous square brackets may well be code generated by a tool. Management Studio puts them on when generating some scripts.

Martin Smith
But I’ve also seen quite a few queries ( not automatically generated by some tool ) where square brackets where enclosing table/column names, even though names didn’t use reserved words or illegal character. Are perhaps brackets also added just for readability?
AspOnMyNet
I guess that's just a question of taste. I don't personally put them on because I'm lazy and don't like typing. Also if you ever use the "design query in editor facility" in SSMS it will strip them all off.
Martin Smith
thank you both for your help
AspOnMyNet
+1  A: 

Brackets are not just for legal characters but to allow the use of otherwise reserved words for column names, etc.

Joe