I have a dynamic query which gets certain records from another database (database server and database name are variables, hence used dynamic query).
Below is the query
DECLARE @SQLString NVARCHAR(1000)
set @SQLString='
select distinct(select distinct
(
select * from
(
------- Inner query (It is more complex than this)
select lAccountId, sAccountName
from '+@DatabaseServer+'.'+@DatabaseName+'.dbo.AccDetails
where lAccountId = 10
union
select lAccountId, sAccountName
from '+@DatabaseServer+'.'+@DatabaseName+'.dbo.AccHistoryDetails
where lAccountId = 10
) A
for xml raw(''Account''), ROOT(''Accounts''), ELEMENTS
)) as AccXmlValue,
lAccountId as AccountId
into
#tmpAccDetails
from
AccountDetails
where
AccountDetails.laccountID in (''10,11'')'
EXECUTE (@SQLString)
----- This is the final SQL statement (It is more complex than this)
select * from
MainAccTable M
inner join #tmpAccDetails tmp on M.lAccountId = tmp.AccountId
I want to use the #tmpAccDetails in join with MainAccTable.
- How can I achieve this, as the temp table will not be in scope outside the dynamic SQL?
- Using Global Temp table solves this, but will it be a good idea to use it in this scenario?
My question is similar to this Question here, except for the fact that I will have to use the #tmpAccDetails table in join, rather than selecting the data from this at one go.
Any help will be appreciated. Thanks.