Reputation:
Instead of this:
-- Method call
SELECT @FunctionResult = DWH_Staging.adm.SalesPlanExists(@Year, @Month, @CountryID, @Type)
I want to use something like this:
DECLARE
@TestedDatabase = 'DWH_Staging',
@TestedSchema = 'adm',
@TestedObject = 'SalesPlanExists'
DECLARE @sql NVARHCAR(4000) = '@TestedDatabase+'.'+@TestedSchema+'.'+@TestedObject (@Year, @Month, @CountryID, @Type)'
-- Method call
SELECT @FunctionResult = @sql
Hints would be appreciated.
Upvotes: 0
Views: 5147
Reputation: 46203
Below is a parameterized SQL example, guessing at your data types:
DECLARE
@TestedDatabase sysname = 'DWH_Staging'
,@TestedSchema sysname = 'adm'
,@TestedObject sysname = 'SalesPlanExists'
,@FunctionResult int
,@Year int
,@Month int
,@CountryID int
,@Type int;
DECLARE @sql nvarchar(MAX) = N'SELECT @FunctionResult = '
+QUOTENAME(@TestedDatabase)
+N'.'
+QUOTENAME(@TestedSchema)
+N'.'
+QUOTENAME(@TestedObject)
+ N'(@Year, @Month, @CountryID, @Type)';
SELECT @sql
-- Method call
EXECUTE sp_executesql
@sql
,N'@FunctionResult int OUTPUT
,@Year int
,@Month int
,@CountryID int
,@Type int'
,@FunctionResult = @FunctionResult OUTPUT
,@Year = @Year
,@Month = @Month
,@CountryID = @CountryID
,@Type = @Type;
Upvotes: 2
Reputation: 1212
What you can do is to set a template for the query, and replace the string while execution:
DECLARE @sql NVARHCAR(4000) = '{DATABASENAME}.{SCHEMANAME}.{OBJECTNAME} (' + @Year + ', ' + @Month + ', ' + @CountryID + ', ' + @Type + ')'
SET @SQL_SCRIPT = REPLACE(@sql, '{DATABASENAME}', @DBNAME)
and then, execute it:
EXECUTE (@SQL_SCRIPT)
Upvotes: 2