I have a stored procedure that is being called by an app from different environments (DEV/QA). From the stored procedure below, I wanted to pass the server name as a parameter, replacing "HARDCODEDSERVER" with the one passed as parameter "@Server"
CREATE PROCEDURE sp_MySTOREDPROCEDURE
@Id Int,
@Server nvarchar(20)
AS
BEGIN
DECLARE @TempTable Table (
-- Declarations
)
DECLARE @TempTable2 Table (
-- Declarations
)
INSERT INTO @TempTable
SELECT a.* FROM Table a
Inner Join [HARDCODEDSERVER].[DatabaseName].dbo.[TABLE1]
-- And so ON
INSERT INTO @TempTable2
SELECT b.* FROM Table b
Inner Join [HARDCODEDSERVER].[DatabaseName].dbo.[TABLE1]
-- And so ON
BEGIN TRANSACTION
BEGIN
UPDATE @TempTable -- rest of the process for TempTable
UPDATE @TempTable2 -- rest of the process for TempTable2
-- The rest of the SP
END
COMMIT TRANSACTION
END
I have used the dynamic SQL approach, but this doesn't work since it cannot scope @TempTable even previously defined already:
DECLARE @SQL nvarchar(2000);
SET @SQL = '
INSERT INTO @TempTable
SELECT a.* FROM Table a
Inner Join [ ' + @Server + '].[DatabaseName].dbo.[TABLE1]
-- And so on
'
EXECUTE sp_executesql @SQL
Tried the same for EXEC but same issue where it can't find @TempTable:
EXEC ( '
INSERT INTO @TempTable
SELECT a.* FROM Table a
Inner Join [ '' + @Server + ''].[DatabaseName].dbo.[TABLE1]
-- And so on
')
I have checked other answers here in SO but most only works on single operations. Any help where the server name can be parameterized and still be able to work/scope on the Temp Tables?