Question about the use of [] in queries...

  • This may seem like a silly question, and I suspect I know the answer (or at least partially) but:

    Why do some scripts wrap certain items in square brackets [], and some don't?

    Using this (partial) query as an example:

    CREATE LOGIN [LoginWithControl] WITH PASSWORD...

    Which is functionally equivalent to (I know, I tested this on my local instance):

    CREATE LOGIN LoginWithCont WITH PASSWORD

    Is it just a way to keep items (as in this case a username) easily identifiable in the code? Somewhat along the lines of indenting code when you break it up between lines?

    Thanks,

    Jason A

  • It's so that illegal identifiers won't break queries.

    CREATE LOGIN [!2hjasdsss.lksks stupid] WITH PASSWORD ...

    will work fine

    CREATE LOGIN !2hjasdsss.lksks stupid WITH PASSWORD ...

    Msg 102, Level 15, State 1, Line 7

    Incorrect syntax near '!'.

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass
  • Thank you!

    Now to get myself into the habit of using them...

    Jason A

  • Personally the only time I use them is when I have an object named with an 'illegal' name or when I'm writing generic (and dynamic) SQL and don't know what object names will be encountered. Other than that, I name objects legally and avoid reserved words, hence don't need []

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply