How to use & (ampersand) character in table name in dynamic sql?

拟墨画扇 提交于 2021-02-10 14:30:02

问题


I am using dynamic SQL to Select from a group of tables where some of the table names contain the '&' character. However once my query hits one of these tables I get the following error:

Incorrect syntax near '&'.

Here is some example code that recreates the error I am getting:

DECLARE @TABLE_NAME AS NVARCHAR(150);
SET @TABLE_NAME = 'A&BTable';

EXEC(
    'SELECT col1, col2, col3
     FROM Warehouse_Repository.dbo.' + @TABLE_NAME
)

How can I alter this query so that I can Select from table names containing '&' using dynamic SQL?


回答1:


Add a QUOTENAME

    DECLARE @TABLE_NAME AS NVARCHAR(150);
    SET @TABLE_NAME = QUOTENAME('A&BTable');

    EXEC(
        'SELECT col1, col2, col3
         FROM dbo.' + @TABLE_NAME
    )


来源:https://stackoverflow.com/questions/48306717/how-to-use-ampersand-character-in-table-name-in-dynamic-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!