CTE具有动态变量

时间:2014-01-15 17:24:04

标签: sql-server tsql dynamic common-table-expression

我有CTE语句的这两个例子,一个是硬编码的,另一个是动态的。硬编码的作品,但不是动态的。你能检查一下我的动态陈述有什么问题吗?感谢

- 这个工作

WITH CTE AS 
( 
SELECT TOP 1 * 
FROM Citi_v823_21Nov2013.dbo.GroupRelation_Audit
WHERE Citi_v823_21Nov2013.dbo.GroupRelation_Audit.ParentEntityIDCounter =   @ParentEntityIDCounter
AND Citi_v823_21Nov2013.dbo.GroupRelation_Audit.ChildEntityIDCounter =    @ChildEntityIDCounter
AND IsNull(Citi_v823_21Nov2013.dbo.GroupRelation_Audit.AuditDateModified, '1900-01-01') < GETDATE()
ORDER BY GroupRelationCounter DESC
) 
UPDATE CTE SET DateEffectiveTo = @DateEffectiveFrom_GroupRelation

- 这不起作用

DECLARE @TargetDB NVARCHAR(Max)
DECLARE @SourceDB NVARCHAR(Max)
DECLARE @DateEffectiveFrom_GroupRelation DATETIME
DECLARE @UpdateRecords_GroupRelation NVARCHAR(Max) 
SET @TargetDB = 'Citi_v823_21Nov2013'
SET @SourceDB = 'UATCitiv82320131018'
SET @DateEffectiveFrom_GroupRelation = '2013-09-29'
SET @UpdateRecords_GroupRelation = '
;WITH CTE AS 
( 
SELECT TOP 1 * 
FROM ' + @TargetDB +  '.dbo.GroupRelation_Audit
WHERE ' + @TargetDB +  '.dbo.GroupRelation_Audit.ParentEntityIDCounter =  ' +   CONVERT(NVARCHAR(Max), @ParentEntityIDCounter) +'
AND ' + @TargetDB +  '.dbo.GroupRelation_Audit.ChildEntityIDCounter = ' +   CONVERT(NVARCHAR(Max), @ChildEntityIDCounter) +'
AND  IsNull(' + @TargetDB +  '.dbo.GroupRelation_Audit.AuditDateModified, ''1900-01-01'') < GETDATE() ''
ORDER BY ' + @TargetDB +  '.dbo.GroupRelation_Audit.GroupRelationCounter DESC
)'
UPDATE CTE SET DateEffectiveTo =  @DateEffectiveFrom_GroupRelation 

EXEC sp_executesql @UpdateRecords_GroupRelation 

1 个答案:

答案 0 :(得分:0)

在SQL语句中移动UPDATE语句。

CTE是本地范围的,因此该语句不知道CTE是什么,只会引发无效的对象错误。

示例代码:

declare @sql nvarchar(max)

select *
into ##t
from
(select 3 as b) tmp

select * from ##t;

set @sql = ';WITH a as (select 1 as b) update ##t set b = (select top 1 * from a) '

EXEC sp_executesql @sql

select * from ##t

drop table ##t