在循环MS SQL中插入记录

时间:2017-12-08 12:27:00

标签: sql-server tsql

还有SQL。 我的情况。 我需要插入表格。我有条件。 如果在一周和一个月中等于它们的费率,一些插入可以做。 例如:对于第2类费率=每月1次。所以我需要在四月才插入一次。但在我的情况下,它插入了我预期的1条记录,并且还插入了5次。

    
 SET @Rate_Init = 1 
 DECLARE @Min_Amount INT = (SELECT T.AccountMin FROM Transactions T 
 FULL JOIN Marathon.dbo.Categories C ON C.CategoryName = 
 T.OperationName WHERE C.CategoryID = @External_Loop_Counter)
 DECLARE @Max_Amount INT = (SELECT T.AccountMax FROM Transactions T 
 FULL JOIN Marathon.dbo.Categories C ON C.CategoryName = 
 T.OperationName WHERE C.CategoryID = @External_Loop_Counter)
 DECLARE @Check_Period NVARCHAR(10) = (SELECT Period  FROM (SELECT * 
 FROM Transactions T FULL JOIN Marathon.dbo.Categories C ON 
 C.CategoryName = T.OperationName) X WHERE CategoryID = 
 @External_Loop_Counter)            
 DECLARE @Frequency INT = (SELECT Rate  FROM (SELECT * FROM 
 Transactions T FULL JOIN Marathon.dbo.Categories C ON C.CategoryName 
 = T.OperationName) X WHERE CategoryID = @External_Loop_Counter)
 WHILE @Total_Dates >= @Internal_Loop_Counter
                    BEGIN

                    IF(@Frequency <= @Rate_Init)
                        BEGIN
                        INSERT INTO Transactions (TransactionDate, TransactionAmount, CategoryID)
                        VALUES((DATEADD(DAY, @Internal_Loop_Counter, @Start_DT)), (@Max_Amount - CAST(((@Max_Amount - @Min_Amount)) AS FLOAT)*RAND()),
                        (SELECT CategoryID FROM (SELECT * FROM Transactions T FULL JOIN Marathon.dbo.Categories C ON C.CategoryName = T.OperationName) X WHERE CategoryID = @External_Loop_Counter))
                        END 

                        SET @Rate_Init = @Rate_Init + 1
                    SET @Jump_Ratio = (
                    CASE
                    WHEN @Check_Period = 'Week' THEN (@Internal_Loop_Counter + CAST(CAST(@Week_T AS FLOAT)*RAND() AS INT))
                    WHEN @Check_Period = 'Month' THEN (@Internal_Loop_Counter + CAST(CAST(@Month_T AS FLOAT)*RAND() AS INT))
                    WHEN @Check_Period = 'Year' THEN (@Internal_Loop_Counter + CAST(CAST(@Year_T AS FLOAT)*RAND() AS INT))
                    END
                    )

                    SET @Internal_Loop_Counter = @Jump_Ratio + 1
                    END

期望 140 2012-03-28 00:00:00 628 2

141 2012-04-26 00:00:00 334 2

142 2012-05-03 00:00:00 418 2

我得到的实际结果

140 2012-03-28 00:00:00 628 2

141 2012-04-03 00:00:00 592 2

142 2012-04-04 00:00:00 353 2

143 2012-04-10 00:00:00 403 2

144 2012-04-16 00:00:00 635 2

145 2012-04-22 00:00:00 673 2

146 2012-04-26 00:00:00 334 2

147 2012-05-03 00:00:00 418 2

使用2017 MS SQL

1 个答案:

答案 0 :(得分:0)

我解决了我的问题。我在外部循环中使用了2个内部循环。当然,不要忘记改变循环的步骤 PS这里没有什么区别 - 完全或内部连接