Square Brackets in SQL Server 2012

Square brackets are one of the worst things that Microsoft has put into SQL server. When you execute a query in SQL, you often have already noticed a common error when creating a table and the table name contains a space like Student table. It will show an error message like "Incorrect syntax near table". It's because of square brackets. The solution is very simple, put the table name in square brackets. You might encounter columns named as keywords. In that case also you need to use square brackets for that particular column name. So let's have a look at a practical example of where to use square brackets in SQL Server 2012. The example is developed in SQL Server 2012 using the SQL Server Management Studio.  

Square Brackets can be used in a variety of situations.

Problem 1: Creating a table in SQL Server

When you create a table and the table name contains a space like in Student table, it will show an error message like "Incorrect syntax near table". The following creates a table script:

CREATE TABLE student table

(

            [stu_id] [int] NULL,

            [stu_name] [varchar](20) NULL,

            [marks] [int] NULL,

            [Remarks] [varchar](50) NULL

)

Now press F5 to execute it. It will show an error message.

 

Table-column-error-in-SQL-Server.jpg

 

The above error is because of square brackets. The solution is very simple, put the table name in square brackets.

 

CREATE TABLE [student table]

(

            [stu_id] [int] NULL,

            [stu_name] [varchar](20) NULL,

            [marks] [int] NULL,

            [Remarks] [varchar](50) NULL

)

 

Now press F5 to execute it.

 

Table-column-With-square-bracket-in-SQL-Server.jpg

Problem 2: Using columns name as keywords

You define a column name that is also a keyword. It will show an error message like "Incorrect syntax near keyword". The following creates a table with a column named FROM which is a keyword script:

Create TABLE [student table]

(

            [stu_id] [int] NULL,

            [stu_name] [varchar](20) NULL,

            [marks] [int] NULL,

            [Remarks] [varchar](50) NULL,

            From  [varchar](20) NULL

)

 

Now Press F5 to execute it. It will show an error message.


Table-column-error-in-SQL-Server.jpg

 


 

The above error is because of square brackets. The solution is very simple, put the table name in square brackets.

 

Create TABLE [student table]

(

            [stu_id] [int] NULL,

            [stu_name] [varchar](20) NULL,

            [marks] [int] NULL,

            [Remarks] [varchar](50) NULL,

            [From]  [varchar](20) NULL

)

 

Now Press F5 to execute it.

 

Table-column-With-square-bracket-in-SQL-Server.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all