Search code examples
sqlsql-server-cebracketsdmlsquare-bracket

Why do my "safety brackets" actually PREVENT this SQL from Working?


I've got some code that had previously apparently needed to have brackets applied to a SQL statement due to a column named "Name"; the "fixed" code was:

dynSQL = string.Format("DELETE FROM Platypi WHERE duckbill = '{0}' and [Name] = '{1}'", tmpType, tmpStr);

Unfortunately, this code was not doing its job - the record was not being deleted. Removing the brackets around the "Name" column:

dynSQL = string.Format("DELETE FROM Platypi WHERE duckbill = '{0}' and Name = '{1}'", tmpType, tmpStr);

...caused it to work. Why would adding the "suspenders" to the column name cause the column to be unrecognized? An answer to a question here indicates that encasing column names (and table names) in brackets is a safe way to avoid naming collisions with other objects/database keywords and such.

When the SQL with the brackets fails, no err msg is displayed, it just doesn't work.

Note, though, that this is inconsistent; sometimes the SQL which contains the "[Name]" as opposed to "Name" works fine - IOW, sometimes the same SQL statement with the same val for "duckbill" but a different one for "Name" works; with "valerie" it fails (when the column named "Name" is bracketed).


Solution

  • Here we go. Looks like brackets aren't supported. Use double quotes instead.

    http://technet.microsoft.com/en-us/library/ms174147(v=sql.110).aspx