将动态值用于我代码中后续动态查询中使用的变量

Use dynamic value to a variable which is being used in the subsequent dynamic query in my code

此代码在设置 @ToDate = '20200311' 时有效,即当我对特定日期进行硬编码时,但在我希望它始终执行到当前日期时无效

set @ToDate = select .....getdate.. 抛出错误,你能帮我解决一下吗?

While @@Fetchstatus =0,

begin 
  set @Fromdate = '20180102';
  set @ToDate = select convert (varchar, getdate(), 112);

  while (@Fromdate < @ToDate) begin
         set @StrQuery = 'INSERT into dbo.Tmp_M_Rates (Rate_Date, Rate_D, Entity, cur) values ('
                         +''''+ CAST (@FromDate AS nvarchar) + ''', ''' + Substring (CONVERT (VARCHAR 
                         (10), @Fromdate, 112),3,8) + ''', ''' + @EntityName + ''', ''' + @Cur + 
                          ''')'
      EXEC (@StrQuery)

      set @Fromdate = dateadd(DAY,1,@Fromdate)
end

您可以将其表述为没有动态的单个查询 SQL:

WITH dates as (
      SELECT CONVERT(date, '20180102') as dte
      UNION ALL
      SELECT dateadd(day, 1, dte)
      FROM CTE
      WHERE dte <= GETDATE()
     )
INSERT into dbo.Tmp_M_Rates (Rate_Date, Rate_D, Entity, cur)
    SELECT dte, SUBSTRING(CONVERT(VARCHAR(10), @Fromdate, 112), 3, 8),
           @EntityName, @Cur
    FROM dates
    OPTION (MAXRECURSION 0);

我强烈建议您采用这种或类似的方法。

如果 Gordon 的回答有正确的想法,更好的方法是不使用任何类型的递归。 SQL 服务器是为基于集合的方法设计的,所以你真的应该使用一个。

您在这里想要的方法是 Tally,它不是递归的,并且默认情况下不限于 100 个循环(如 rCTE),因为它不会循环:

DECLARE @FromDate date = '20180102';

WITH N AS(
    SELECT N
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
Tally AS(
    SELECT TOP (DATEDIFF(DAY,@FromDate, GETDATE())+1)
           ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS I
    FROM N N1, N N2, N N3), --1000 rows, add more cross joins to N for more rows
Dates AS(
    SELECT DATEADD(DAY, T.I, @FromDate) AS D
    FROM Tally T)
INSERT INTO dbo.Tmp_M_Rates (Rate_Date, Rate_D, Entity, cur)
SELECT D,
       SUBSTRING(CONVERT(VARCHAR(10), @Fromdate, 112), 3, 8),
       @EntityName,
       @Cur
FROM Dates;

只是另一个带有临时 tally/numbers table

的选项

例子

Declare @Date1 date = '2018-01-02'
Declare @Date2 date = getdate()
Declare @Entity varchar(50) ='Entity Name'
Declare @Cur    varchar(50) ='USD'

--INSERT into dbo.Tmp_M_Rates (Rate_Date, Rate_D, Entity, cur) 
Select Rate_Date = D
      ,Rate_D    = dateadd(DAY,1,D)
      ,Entity    = @Entity
      ,Cur       = @Cur
 From (
         Select Top (DateDiff(DAY,@Date1,@Date2)+1) 
               D=DateAdd(DAY,-1+Row_Number() Over (Order By (Select Null)),@Date1) 
         From  master..spt_values n1,master..spt_values n2
      ) A

为 INSERT

生成以下内容