What is the use of the square brackets [] in sql s

2019-01-02 18:31发布

I've noticed that Visual Studio 2008 is placing square brackets around column names in sql. Do the brackets offer any advantage? When I hand code T-SQL I've never bothered with them.

Example: Visual Studio: SELECT [column1], [column2] etc...

My own way: SELECT column1, column2 etc...

9条回答
步步皆殇っ
2楼-- · 2019-01-02 18:37

In addition Some Sharepoint databases contain hyphens in their names. Using square brackets in SQL Statements allow the names to be parsed correctly.

查看更多
情到深处是孤独
3楼-- · 2019-01-02 18:38

The brackets are required if you use keywords or special chars in the column names or identifiers. You could name a column [First Name] (with a space)--but then you'd need to use brackets every time you referred to that column.

The newer tools add them everywhere just in case or for consistency.

查看更多
查无此人
4楼-- · 2019-01-02 18:41

During the dark ages of SQL in the 1990ths it was a good practice as the SQL designers were trying to add each word in the dictionary as keyword for endless avalanche of new features and they called it the SQL3 draft.

So it keeps forward compatibility.

And i found that it has another nice side effect, it helps a lot when you use grep in code reviews and refactoring.

查看更多
其实,你不懂
5楼-- · 2019-01-02 18:44

They are useful if you are (for some reason) using column names with certain characters for example.

Select First Name From People

would not work, but putting square brackets around the column name would work

Select [First Name] From People

In short, it's a way of explicitly declaring a object name; column, table, database, user or server.

查看更多
与风俱净
6楼-- · 2019-01-02 18:44

The brackets can be used when column names are reserved words.

If you are programatically generating the SQL statement from a collection of column names you don't control, then you can avoid problems by always using the brackets.

查看更多
其实,你不懂
7楼-- · 2019-01-02 18:53

I believe it adds them there for consistency... they're only required when you have a space or special character in the column name, but it's cleaner to just include them all the time when the IDE generates SQL.

查看更多
登录 后发表回答