Blog Pages

Error message when execute USE DB

If DB name include special characters (like '-', '.'), error messages will be displayed when execute:
USE Ddddd.7 
--> error msg: Incorrect syntax near '.7'.

The problem is in the DB name.
Solution:
USE [Ddddd.7]


It can be more dangerous when execute it in dynamic SQL:
DECLARE @DBName nvarchar(128) = DB_NAME()
DECLARE @Sql nvarchar(500)
SET @Sql = 'USE ' + @DBName + ........
EXEC (@SQL)
--> error msg: Incorrect syntax near '.7'.

It recommended to write it in this syntax:
.....
SET @Sql = 'USE [' + @DBName + ']'  + ........
EXEC (@SQL)

No comments:

Post a Comment