1

我有下表:

VehicleID Reg_ID Next_RegID EntryDate
330034    9111   NULL        2010-12-06 00:00:00
330034    9113   NULL        2010-12-09 00:00:00

在第一行,我需要使用第二行的 Reg_ID 更新 Next_RegId 列,其中 VehicleId 或 (VIN/ChassisNumber) 相同。最后一个条目上的 Next_RegID 列应保持为 Null。

我创建了一个运行良好的 while 循环过程,但是表中有数百万条记录需要很长时间才能完成。因此,我想知道你们中是否有人处理过这种问题并有解决方案。

这是我写的程序,在此先感谢您的帮助:

Declare @i as integer;
Declare @x as integer;
Declare @y as integer

Set @i= (Select Max(RID) from TempRegistration)
Set @x= 0
Set @y= 1
Declare @curChassis as nvarchar(100)
Declare @nextChassis as nvarchar(100)

  While (@x <= @i)
  Begin
set @curChassis = (Select ChassisNumber from TempRegistration where RID = @x)
set @nextChassis = (Select ChassisNumber from TempRegistration where RID = @y)

If (@curChassis = @nextChassis)
Begin
    Update Registration set NextRegistrationId = (Select RegistrationId from      TempRegistration where RID = @y)
    Where RegistrationId = (Select RegistrationId from TempRegistration where RID = @x)
End

Set @x = @x + 1
Set @y = @y + 1

Print(@x)
    End

TempRegistration 是我创建的一个临时表,用于分配一个 row_id,它指导 while 循环将 Reg_ID 分配给前一行的 Next_RegId。

4

2 回答 2

0

这可以通过一个 UPDATE 查询来完成。你还没有提到你的RDBMS,所以......

对于 MSSQL:

Update Registration as t1
set NextRegistrationId = (Select TOP 1 RegistrationId 
                                       from Registration
                                       where RID = t1.RID 
                                         and EntryDate>t1.EntryDate
                                       order by EntryDate DESC)

对于 MySQL

Update Registration as t1
set NextRegistrationId = (Select RegistrationId 
                                       from Registration 
                                       where RID = t1.RID 
                                          and EntryDate>t1.EntryDate
                                       order by EntryDate DESC 
                                       LIMIT 1)

如果 RID 随着 EntryDate 的增加而增加,那么

Update Registration as t1
set NextRegistrationId = (Select MIN(RegistrationId) 
                                       from Registration 
                                       where RID = t1.RID
                                       and EntryDate>t1.EntryDate
                          )
于 2013-09-20T08:39:28.743 回答
0

经过测试,它似乎可以正常工作,但此版本使用CTE(SQL Server)

with RegDetails as
(
select VehicleID, Reg_ID, ROW_NUMBER() OVER(PARTITION BY VehicleID ORDER BY EntryDate) AS ROWNUMBER
FROM dbo.Vehicle)
UPDATE a SET a.Next_RegID = b.Reg_ID
FROM RegDetails b
INNER JOIN dbo.Vehicle a ON (a.VehicleID = b.VehicleID)
WHERE b.ROWNUMBER = 2 and a.Next_RegID IS NULL and a.Reg_ID != b.Reg_ID
于 2013-09-20T14:39:13.087 回答