如何使用动态SQL字符串?

时间:2018-02-02 13:23:27

标签: sql-server tsql dynamic-sql

而不是:

-- Method call
SELECT @FunctionResult = DWH_Staging.adm.SalesPlanExists(@Year, @Month, @CountryID, @Type)

我想使用这样的东西:

DECLARE
    @TestedDatabase = 'DWH_Staging',
    @TestedSchema   = 'adm',
    @TestedObject   = 'SalesPlanExists' 

DECLARE @sql NVARHCAR(4000) = '@TestedDatabase+'.'+@TestedSchema+'.'+@TestedObject (@Year, @Month, @CountryID, @Type)'

-- Method call
SELECT @FunctionResult = @sql

提示将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以做的是为查询设置模板,并在执行时替换字符串:

DECLARE @sql NVARHCAR(4000) = '{DATABASENAME}.{SCHEMANAME}.{OBJECTNAME} (' + @Year + ', ' + @Month + ', ' + @CountryID + ', ' + @Type + ')'
SET @SQL_SCRIPT = REPLACE(@sql, '{DATABASENAME}', @DBNAME)

然后执行它:

EXECUTE (@SQL_SCRIPT)

答案 1 :(得分:1)

下面是一个参数化的SQL示例,猜测您的数据类型:

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;