T-SQL动态变量插入

时间:2014-11-12 15:51:39

标签: sql sql-server stored-procedures dynamic-sql

使用此查询,

可以帮助一些人。我的临时表中有10行

Declare @date date = '2014-11-01'
Declare @iDate int = '20141101'
Create table #test33(Paname  varchar(100))
insert into #test33

Go

现在我在临时表中有10行。我想在动态cte中插入那些临时值

Declare @StartDate date = '2014-11-01'
Declare @EndDate date = '2014-11-30'
Declare @Paname   nvarchar(100) = 'MPU' --- i have  multiple panames how can i insert dyamically in cte or any other solution?



 ;with pla as
          (     SELECT*
          FROM  [dbo].[Pla] pl
                 JOIN dbo.testplan cl
                 ON pl.ClientId = cl.ClientId
                 where  pl.name = @Paname  
                 and pl.StartDate >= @StartDate and pl.EndDate <= @EndDate
                 ) 
   select * from pla

1 个答案:

答案 0 :(得分:0)

您可以使用WHILE或使用CURSOR循环遍历多个参数。在其中你可以使用动态sql:

declare @DSQL varchar(MAX)

SET @DSQL = ';with pla as
            (     SELECT*
                  FROM  [dbo].[Pla] pl
                  JOIN dbo.testplan cl
                  ON pl.ClientId = cl.ClientId
                  where  pl.name = '+@Paname+' 
                  and pl.StartDate >= '+@StartDate+' and pl.EndDate <= '+@EndDate+'
                  ) 
               select * from pla'
EXEC(@DSQL)