SQL中的预期ID或Quoted_ID

时间:2014-08-28 03:02:49

标签: sql sql-server-2008 tsql

我收到以下错误:

"Incorrect Syntax near '.'. Expected ID or Quoted_ID".

尝试创建以下程序时,

CREATE PROCEDURE [dbo].[SP_NAME]
@DBName varchar(max)
As
Begin

SELECT NBCGL_TRANSACTION.*, MRG_BSLA.GL_BSLA_CODE AS BSLA 
FROM @DBName..NBCGL_TRANSACTION LEFT OUTER JOIN MRG_BSLA 
     ON NBCGL_TRANSACTION.BUSINESS = MRG_BSLA.BSLA_CODE 
WHERE NBCGL_TRANSACTION.TRANSACTION_TYPE = 2 

END

1 个答案:

答案 0 :(得分:8)

您不能直接使用变量作为数据库/模式/表/列名称。您需要使用动态SQL来实现目标:

CREATE PROCEDURE [dbo].[SP_NAME]
@DBName varchar(max)
As
Begin

declare @query nvarchar(max) 
set @query = N'SELECT NBCGL_TRANSACTION.*, MRG_BSLA.GL_BSLA_CODE AS BSLA FROM ' 
+ @DBName
+ N'..NBCGL_TRANSACTION LEFT OUTER JOIN MRG_BSLA ON NBCGL_TRANSACTION.BUSINESS = MRG_BSLA.BSLA_CODE WHERE NBCGL_TRANSACTION.TRANSACTION_TYPE = 2' 

exec sp_executesql @query

END