views:

92

answers:

4

I'm working on some legacy SQL and the author delimited every column name and 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?

+2  A: 

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.

marc_s
+1: Maintaining current practices is good - it's likely not just you handling this stuff.
OMG Ponies
+8  A: 

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.

Marcus
[And] [it] [also] [makes] [it] [much] [harder] [to] [type] [in] [your] [code]
Philip Kelley
Agree with both of you... clutters code and bollixes up double-click-select-too
gbn
Well.. we use an ORM, so there's no SQL in any of our production code and I don't have to worry about clutter. So I only write SQL once in a blue moon; however, we do write the database object creation and modification scripts by hand and keep them in version control, so I want to make sure those are up to snuff.
Travis Heseman
Now, that I've done some digging, it appears that these statements were generated by SSMS, but we modify them by hand as the schema evolves and check those changes into SVN. I'll proceed with the current practice, but hand-written scripts will not have the bracket clutter. Thanks
Travis Heseman
A: 

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.

Jordan
A: 

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.

Eoin