One of the ways to do this is to create a String dynamically and use the Stored Procedure sp_executesql
to execute the SQL that is in this string.
Take 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 I was doing a long time ago in SQL Server 2005. I don’t know if in newer versions there are easier ways to do.
I also used this for cases where the Stored Procedure should run in separate databases (although in the same instance). Thus, even the name of the bank was possible to parameterize. See example:
'FROM [' + @DATABASE + '].[dbo].[' + @TABELA_CT2 + '] CT2, [' + @DATABASE + '].[dbo].[CTS020] CTS'
You’re using Stored Procedures?
– Marconi
Do not forget to mark the question as answered if you found any alternative the was satisfactory
– jefissu
@Jefissu doesn’t even vote on the answer he voted, imagine choose the answer.
– Marco Souza