开发者

Are delimited identifiers considered a "best-practice" in Transact-SQL?

开发者 https://www.devze.com 2022-12-13 06:14 出处:网络
I\'m working on some legacy SQL and the author delimited every column name a开发者_如何转开发nd data type declaration. See the following:

I'm working on some legacy SQL and the author delimited every column name a开发者_如何转开发nd data type declaration. See the following:

CREATE TABLE SomeTable (
    [SomeDate]   [datetime] NOT NULL,
    [SomeInt]    [int]      NOT NULL,
    [SomeString] [nvarchar] NOT NULL
) ON [PRIMARY]
GO

Is this considered a best-practice when writing T-SQL for SQL Server? Since I'm now maintaining this code, should I continue the practice?


I personally would only write that if you're using reserved keywords as column/table names, which you shouldn't be anyway. Personally I think otherwise, it makes the SQL code less 'clean' and a bit more difficult to read.

This style is usually what is generated by SQL tools, as it guarantees that there won't be any issues with reserved word conflicts.


If the name of the table or column is "harmless" like "SomeInt", then the square brackets [...] aren't required - you can specify them, if you want to, don't have to.

On the other hand - always using those will make sure that even "dangerous" column names like '[Message]' and others, or column names with spaces in them like [Product Name], will always be handled correctly.

So - you don't have to continue doing it, but I would think it's a good practice and if it's already been used, I'd recommend to keep using it.


Most of the MS tools I've worked with that generate SQL will do this automatically (the old Query Analyzer, Management Studio, etc.) It doesn't hurt.


Just starting out with mssql/t-sql and the solution maybe to use single quotes when needed as this covers both the deprecated square-bracket style and the new double quotes style. Quote me if I am wrong!

A simple example.

1> sp_help sys.tables
2> go
Msg 102, Level 15, State 1, Server
Incorrect syntax near '.'.
1> sp_help 'sys.tables'
2> go
Name                           Owner
------------------------------ ----
tables                         sys
etc


The [SomeName] is what is produced by the automatically generated scripts from SQL Server Management Studio. Personally I find it distracting and makes the names more difficult to read.

The only real use for them is to allow spaces in identifiers.

i.e.

create table SomeTable
(
   [some var] int
)

is valid (though inadvisable) while

create table SomeTable
(
   some var int
)

is invalid.

So it would be useful for porting/mainting legacy projects.

0

精彩评论

暂无评论...
验证码 换一张
取 消