Bracket around database name in SQL Server [duplicate]

55ooxyrt  于 2023-11-16  发布在  SQL Server
关注(0)|答案(2)|浏览(143)

This question already has answers here:

What is the use of the square brackets [] in sql statements? (10 answers)
Closed 14 days ago.

When I want to use one of my databases, I should to write this query:

USE DatabaseName;

but when I was trying to type this query my SQL Prompt use the correct form of this query which that query is this:

USE [DataBases]

What does this bracket means in this query or in SQL Server queries?

This query is also correct

USE DatabaseName;

but I want to know what the meaning of brackets in SQL Server is or in same queries?

d4so4syb

d4so4syb1#

  1. If you have SQL keyword, space or any other illegal characters then you need to use square brackets.
  2. SQL server parse and compiler much more easy to validate and compile code.
  3. code search tools easy to find table names or column names only.
n53p2ov0

n53p2ov02#

Square brackets are meant to let you treat an object name which would normally not be allowed, as a valid object name. Things like special characters, spaces, and reserved keywords are some good examples.

select [Column with spaces], [1NumberAtTheStart]
from dbo.[User]

If not for square brackets here, none of the quoted objects above would pass as valid object names. The first column has spaces, the second starts with a number, and User is a reserved keyword.

The reason SQLPrompt suggests not using them is that it can make your code look "noisy".

Of course, some times you need them. Say you have a table called dbo.User . If you try to say select * from dbo.User you will get an error. So you MUST quote the object name to keep SQL from freaking out (i.e. select * from dbo.[user] ). It's completely allowable in SQL to quote all your object names if you really want, but it's really meant for if you have object names with spaces, or other characters you need to ignore.

相关问题