我收到以下错误:
"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
答案 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