1

I have db whose name is shreyanshdb] that is it has a closing square bracket. I wanted to perform the backup of this db using SQL query in SQL server. But it is throwing me an exception: Transact-sql exception.

Here is the command : BACKUP DATABASE [shreyanshdb]] to disk = 'c:\DB'

I really don't know how do i escape the closing square bracket...

Mistalis
  • 17,793
  • 13
  • 73
  • 97
  • 1
    Should google "ms sql escape character", [first hit](https://stackoverflow.com/questions/5139770/escape-character-in-sql-server). Not sure if it'll help you, but at least show us what you did try. Flagging question as unclear. – rkeet Jul 31 '17 at 10:03
  • Nothing helpful to add but fascinated to know how the DB got that name and why you can't change it to something less problematic. – LoztInSpace Jul 31 '17 at 12:01

2 Answers2

1

I think you can use sp_executesql for this. Where you pass the databasename as a parameter.

https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql

Mr Zach
  • 495
  • 4
  • 18
  • In SQL server it actually worked with the following command: BACKUP DATABASE "shreyanshdb]" TO DISK = 'D:\LOG_DIR' . How come it worked with double quotes.... Actually i have to execute or write this SQL command in c sharp...so should i append double quotes in the db name... – NewInMachineLearning Jul 31 '17 at 10:44
1
BACKUP DATABASE [shreyanshdb]]] to disk = 'c:\DB'

You can see how things should be quoted from the QUOTENAME function documentation. For rectangular brackets, the closing bracket should be doubled.

It's probably best not to use those brackets, or spaces, or any irregular characters in a database name, table name, column name or any other object name in SQL Server.

TT.
  • 15,774
  • 6
  • 47
  • 88