如何使用动态SQL字符串?
How to use dynamic SQL string?
而不是这个:
-- 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
不胜感激。
你可以做的是为查询设置一个模板,并在执行时替换字符串:
DECLARE @sql NVARHCAR(4000) = '{DATABASENAME}.{SCHEMANAME}.{OBJECTNAME} (' + @Year + ', ' + @Month + ', ' + @CountryID + ', ' + @Type + ')'
SET @SQL_SCRIPT = REPLACE(@sql, '{DATABASENAME}', @DBNAME)
然后,执行它:
EXECUTE (@SQL_SCRIPT)
下面是一个参数化的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;
而不是这个:
-- 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
不胜感激。
你可以做的是为查询设置一个模板,并在执行时替换字符串:
DECLARE @sql NVARHCAR(4000) = '{DATABASENAME}.{SCHEMANAME}.{OBJECTNAME} (' + @Year + ', ' + @Month + ', ' + @CountryID + ', ' + @Type + ')'
SET @SQL_SCRIPT = REPLACE(@sql, '{DATABASENAME}', @DBNAME)
然后,执行它:
EXECUTE (@SQL_SCRIPT)
下面是一个参数化的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;