One of the ways to do this is to create a String dynamically and use Stored Procedure sp_executesql
to execute SQL that is in that String.
See an example:
DECLARE @SQL NVARCHAR(4000)
DECLARE @EH_PORT INT
DECLARE @ID INT
SET @EH_PORT = 2
SET @ID = 15
SET @SQL = 'SELECT * FROM TABELA '
IF @EH_PORT = 2
BEGIN
SET @SQL = @SQL + 'WHERE ID = ' + CAST(@ID AS VARCHAR(10))
END
print @SQL
exec sp_executesql @SQL, N'@ID int',
@ID
This was a long time ago in SQL Server 2005. I do not know if newer versions have easier ways to do it.
I also used this for cases where the Stored Procedure should run into separate databases (albeit on the same instance). Thus, even the name of the bank could be parameterized. See example:
'FROM [' + @DATABASE + '].[dbo].[' + @TABELA_CT2 + '] CT2, [' + @DATABASE + '].[dbo].[CTS020] CTS'