user5021612
user5021612

Reputation:

How to use dynamic SQL string?

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

Answers (2)

Dan Guzman
Dan Guzman

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

Mithgroth
Mithgroth

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

Related Questions