SQL Server:存储过程中的动态数据库名称

时间:2014-01-07 09:02:51

标签: sql-server tsql stored-procedures

我正在使用动态数据库名称创建存储过程。但是在指定参数

之后我无法运行它
@BatchStartTime = N'2013/12/26 15:00:00',
@BatchEndTime = N'2013/12/26 15:30:00',
@DBName = N'MYDATABASE'

以下是我的示例代码:

ALTER PROCEDURE [dbo].[newSpMurexTest]
    @BatchStartTime AS VARCHAR(30),
    @BatchEndTime AS VARCHAR(30),
    @DBName AS VARCHAR(30)
AS  BEGIN
       declare @vwAllTrans nvarchar(max)

       set @vwAllTrans = N'select T.fin_payAmt, C.fin_midAmt, C.myr_equivalent from '+ QUOTENAME(@DBName) +'.dbo.tbl_transaction_history as H 
                       inner join '+ QUOTENAME(@DBName) + '.dbo.tbl_transaction_cancellation as C on H.transaction_id = C.trans_id
                      inner join '+ QUOTENAME(@DBName) +'.dbo.tbl_transaction as T on H.transaction_id = T.transaction_id
                      where  H.dt_last_chg >=  @BatchStartTime  H.dt_last_chg <= @BatchEndTime and (H.new_status IN (7))'

    EXECUTE sp_executesql @vwAllTrans
                          ,'@BatchStartTime AS VARCHAR(30), @BatchEndTime AS VARCHAR(30)'
                          , @BatchStartTime, @BatchEndTime
END

如果我删除@vwAllTrans,我可以运行查询,直接选择它并替换@dbname@BatchStartTime@BatchEndTime ..我是否搞砸了查询什么时候把它放在@vwAllTrans下并执行它?

1 个答案:

答案 0 :(得分:4)

ALTER PROCEDURE [dbo].[newSpMurexTest]
@BatchStartTime  AS NVARCHAR(30),
@BatchEndTime    AS NVARCHAR(30),
@DBName          AS NVARCHAR(30)

AS
BEGIN 
  SET NOCOUNT ON;   

declare @vwAllTrans nvarchar(max)
set @vwAllTrans = N'select T.fin_payAmt, C.fin_midAmt, C.myr_equivalent from '+ QUOTENAME(@DBName) + N'.dbo.tbl_transaction_history as H 
                  inner join '+ QUOTENAME(@DBName) + N'.dbo.tbl_transaction_cancellation as C on H.transaction_id = C.trans_id
                  inner join '+ QUOTENAME(@DBName) + N'.dbo.tbl_transaction as T on H.transaction_id = T.transaction_id
                  where  H.dt_last_chg >=  @BatchStartTime AND H.dt_last_chg <= @BatchEndTime and H.new_status IN (7)'

EXECUTE sp_executesql @vwAllTrans
                      ,N'@BatchStartTime AS NVARCHAR(30), @BatchEndTime AS NVARCHAR(30)'
                      , @BatchStartTime, @BatchEndTime
END

GO