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:59

Column names can contain characters and reserved words that will confuse the query execution engine, so placing brackets around them at all times prevents this from happening. Easier than checking for an issue and then dealing with it, I guess.

查看更多
若你有天会懂
3楼-- · 2019-01-02 19:02

They're handy if your columns have the same names as SQL keywords, or have spaces in them.

Example:

create table test ( id int, user varchar(20) )

Oh no! Incorrect syntax near the keyword 'user'. But this:

create table test ( id int, [user] varchar(20) )

Works fine.

查看更多
琉璃瓶的回忆
4楼-- · 2019-01-02 19:02

Regardless of following a naming convention that avoids using reserved words, Microsoft does add new reserved words. Using brackets allows your code to be upgraded to a new SQL Server version, without first needing to edit Microsoft's newly reserved words out of your client code. That editing can be a significant concern. It may cause your project to be prematurely retired....

Brackets can also be useful when you want to Replace All in a script. If your batch contains a variable named @String and a column named [String], you can rename the column to [NewString], without renaming @String to @NewString.

查看更多
登录 后发表回答