-1

I have a table of new customers in an old legacy system which I need to calculate and update the CustomerID of which is Alphanumeric (5 letters 3 numbers). The legacy system already has a list of customerIDs. I want to update the new customersIDs in line with the existing sequence.

There may also be a 5 letter id which doesn't already exist in the list and would therefore start at 001.

I have the 5 letters for each new customer within a field. I just need to update with the next in sequence.

For example:

ExistingCustomerIDs

ALPHA001
ALPHA002
COLUM001
COLUM002
TESTI001
TESTI002
TESTI003
TESTI004

New Customers Table only contains the beginning 5 letters.

ALPHA   (Should become ALPHA003)
ALPHA   (Should become ALPHA004)
ALPHA   (Should become ALPHA005)
COLUM   (Should become COLUM003)
COLUM   (Should become COLUM004)
TESTI   (Should become TESTI005)
DANIE   (Should become DANIE001)
DANIE   (Should become DANIE002)
4

2 回答 2

0

您可以使用它ROW_NUMBER()来生成新数字,您只需从现有 ID 中可用的上一个最大值开始计数。

设置:

DECLARE @ExistingIDs TABLE (OldCustomerID VARCHAR(10))

INSERT INTO @ExistingIDs (OldCustomerID)
VALUES
    ('ALPHA001'),
    ('ALPHA002'),
    ('COLUM001'),
    ('COLUM002'),
    ('TESTI001'),
    ('TESTI002'),
    ('TESTI003'),
    ('TESTI004')

DECLARE @NewIds TABLE (NewCustomerID VARCHAR(10))

INSERT INTO @NewIds (NewCustomerID)
VALUES 
    ('ALPHA'),('ALPHA'),('ALPHA'),
    ('COLUM'),('COLUM'),
    ('TESTI'),
    ('DANIE'),('DANIE')

解决方案:

;WITH PreviousMax AS
(
    SELECT
        Letters = LEFT(E.OldCustomerID, 5),
        LatestNumber = MAX(CONVERT(INT, RIGHT(E.OldCustomerID, 3)))
    FROM
        @ExistingIDs AS E
    GROUP BY
        LEFT(E.OldCustomerID, 5)
)
SELECT
    N.NewCustomerID,
    UpdatedNewCustomerID = N.NewCustomerID + 
        RIGHT(
            '00' + CONVERT(VARCHAR(3), ISNULL(P.LatestNumber, 0) + ROW_NUMBER() OVER (PARTITION BY N.NewCustomerID ORDER BY (SELECT NULL))),
            3)
FROM
    @NewIds AS N
    LEFT JOIN PreviousMax AS P ON N.NewCustomerID = P.Letters

结果:

NewCustomerID   UpdatedNewCustomerID
ALPHA           ALPHA003
ALPHA           ALPHA004
ALPHA           ALPHA005
COLUM           COLUM003
COLUM           COLUM004
DANIE           DANIE001
DANIE           DANIE002
TESTI           TESTI005
于 2019-02-21T16:19:01.813 回答
0

嗯。您可以通过从现有客户中提取每个客户 ID 的最后一个值来完成此操作。然后将其添加到新客户的枚举中:

with e as (
      select left(customerId, length(customerId) - 3) as base, max(right(customerId, 3)) + 0 as lastnum
      from existing e
      group by left(customerId, length(customerId) - 3)
     ),
     nc as (
      select customerId, row_number() over (partition by customerId order by customerId) as seqnum
      from newcustomers
     )
update nc
    set nc.customerId = nc.customerId + right('000' + convert(varchar(255), seqnum + base))
    from nc join
         e
         on nc.customerId = e.base;
于 2019-02-21T16:13:56.193 回答