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.

2
  • 1
    What do you want to achieve exactly and what is not working? Commented Feb 2, 2018 at 13:25
  • Use an OUTPUT variable when you call sp_executesql stackoverflow.com/questions/803211/… Commented Feb 2, 2018 at 13:28

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

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;

1 Comment

Upvoted for using QUOTENAME; something neglected way too often.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.