简体   繁体   中英

SQL Server : dynamic database name in stored procedure

I'm creating a stored procedure with dynamic db name. But I can't get it run after I specify the parameters

@BatchStartTime = N'2013/12/26 15:00:00',
@BatchEndTime = N'2013/12/26 15:30:00',
@DBName = N'MYDATABASE'

Here are my sample code:

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

I can run the query if I remove the @vwAllTrans , directly select it and replace the @dbname , @BatchStartTime , and @BatchEndTime .. do I mess up the query when it put it under @vwAllTrans and exec it?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM