SQL While循环插入包含来自另一个表的值

时间:2018-05-05 00:54:12

标签: sql sql-server tsql

我正在尝试创建一个SQL While循环,它将使用另一个表中的值更新临时表。来自另一个表的值:

477286
560565
499330
391827
127375
526354
501736
357359
410433
500946
261297
377667
135931
235691
247239
143672
548752
471945
...

写下以下内容,但它只会多次插入最后一个值。

以下是代码:

USE Reports
GO
    CREATE TABLE #TempTable (CreatedByID int, LastUpdatedByID int, ID int, 
AlertDE int, Alert char(50), StartDTTM datetime, EndDTTM datetime, 
IsInactiveFLAG char(1),AlertDetails char(1));
    DECLARE @numrows INT
    SELECT @numrows  = COUNT(*) FROM [Reports].[dbo].[Eligible]
    DECLARE @id int 
    DECLARE @LoopCount INT = 1
    DECLARE @count int = @numrows
    SELECT  @id = [id] FROM [Reports].[dbo].[Eligible]
WHILE (@LoopCount <= @count)
BEGIN  
    INSERT INTO #TempTable (CreatedByID, LastUpdatedByID, ID, AlertDE, Alert, StartDTTM, EndDTTM, IsInactiveFLAG,AlertDetails) 
    VALUES (52,52,@id,0,'Eligible',CURRENT_TIMESTAMP,'1900-01-01 
00:00:00.000','N','') 
    SET @LoopCount = @LoopCount + 1
END 
SELECT * FROM #TempTable
DROP TABLE #TempTable

我假设我必须告诉它以某种方式循环遍历另一个表格中的值,但如果这是正确的方法我不肯定,或者如果一般情况下我在公共汽车上走很长的路。

2 个答案:

答案 0 :(得分:2)

你为什么要使用循环?您可以使用insert . . . select语句执行此操作:

INSERT INTO #TempTable (CreatedByID, LastUpdatedByID, ID, AlertDE, Alert, StartDTTM, EndDTTM, IsInactiveFLAG, AlertDetails) 
    SELECT(52, 52, e.id, 0, 'Eligible', CURRENT_TIMESTAMP, '1900-01-01 00:00:00.000', 'N', ''
    FROM [Reports].[dbo].[Eligible] e ;

答案 1 :(得分:0)

GMR,我找到了一种方法来满足我的需求,这与你的需求类似。希望这对你也有帮助。

DECLARE
  @LoopId  int
 ,@TheOrderNumber  varchar(20)

DECLARE @CheckThisItem TABLE
 (
   LoopId  int  not null  identity(1,1)
  ,TheOrderNumber varchar(20)  not null
 )

INSERT @CheckThisItem 
SELECT Order_Number AS TheOrderNumber
FROM [dbo].[Table_Storing_Order_Number] ORDER BY Order_Number ASC
SET @LoopId = @@rowcount
WHILE @LoopId > 0
   BEGIN  
     SELECT @TheOrderNumber = TheOrderNumber
     FROM @CheckThisItem
     WHERE LoopId = @LoopId
-- Start inserting record pulled for while loop
        INSERT [dbo].[The_Destination_Table]
            SELECT TOP (1)
            A, B, C, D
            FROM [dbo].[Source_Table] ST
            WHERE 
            ST.Order_Number = @TheOrderNumber
        -- Set number to reduce loop counter
    SET @LoopId = @LoopId - 1
 END;