0

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.

  • 1
    What do you want to achieve exactly and what is not working? – Onkel Toob Feb 02 '18 at 13:25
  • Use an `OUTPUT` variable when you call `sp_executesql` https://stackoverflow.com/questions/803211/how-to-get-sp-executesql-result-into-a-variable – Zack Feb 02 '18 at 13:28

2 Answers2

2

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;
Dan Guzman
  • 43,250
  • 3
  • 46
  • 71
1

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)
Mithgroth
  • 1,114
  • 2
  • 13
  • 23