user2085499
user2085499

Reputation: 41

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?

Upvotes: 1

Views: 4035

Answers (1)

M.Ali
M.Ali

Reputation: 69524

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

Upvotes: 4

Related Questions