简体   繁体   English

SQL 服务器:将不存在的号码检查到表中

[英]SQL Server : check not existing number into a table

I have a Clients table already populated by thousands of records and now I need to search for a non-existing number in the card number column starting from the number x .我有一个已经由数千条记录填充的Clients表,现在我需要从数字x开始在card number列中搜索一个不存在的数字。

Example: I would like to search for the first available card number starting from number 2000.示例:我想从号码 2000 开始搜索第一个可用的card number

Unfortunately I cannot select MAX() as there are records with 9999999 (which is the limit).不幸的是,我不能 select MAX()因为有 9999999 的记录(这是限制)。

Is it possible to do this search through a single SELECT ?是否可以通过单个SELECT进行此搜索?

If the credit card is represented as integer in your table and your starting number is 2000 you could do something like:如果信用卡在您的表中表示为 integer 并且您的起始编号是2000 ,您可以执行以下操作:

SELECT top 1 (card_id + 1) 
FROM CreditCards t
WHERE card_id IN (
    SELECT card_id
    FROM CreditCards
    WHERE card_id LIKE '%[2][0][0][0]%'
)
AND NOT EXISTS (SELECT 1 FROM CreditCards t2 WHERE t2.card_id = t.card_id + 1)
ORDER BY card_id

Example data (Table: CreditCards):示例数据(表:信用卡):

card_id card_id
2000002 2000002
2000103 2000103
2000000 2000000
2000108 2000108
20001006 20001006
3000201 3000201

Result is: 2000001结果是:2000001

Note that %[2][0][0][0]% is fixed here.注意%[2][0][0][0]%在这里是固定的。 You could also introduce a parameter.您还可以引入一个参数。

It is not an optimal solution, but it does the work.这不是一个最佳解决方案,但它确实有效。

It's possible with a few nested SELECT s:可以使用一些嵌套的SELECT

SELECT MIN(`card_number`) + 1 as next_available_number
  FROM( SELECT (2000-1) as `card_number`
        UNION
        SELECT `card_number`
        FROM clients
        WHERE `card_number` >= 2000
      ) tmp
  WHERE NOT EXISTS ( SELECT NULL
                   FROM clients
                   WHERE `card_number` = tmp.`card_number` + 1 )

It can be done with a self-join on your clients table, where you search for the lowest cardnumber for which the cardnumber + 1 does not exist.这可以通过clients表上的自联接来完成,您可以在其中搜索不存在cardnumber + 1的最低cardnumber

In case x is 12 , the query would be:如果x12 ,则查询将是:

SELECT MIN(cardnumber) + 1
FROM clients
WHERE cardnumber + 1 NOT IN (SELECT cardnumber FROM clients)
  AND cardnumber + 1 > 12

Eg.例如。 with a dataset of有一个数据集

INSERT INTO clients (cardnumber) VALUES
(1),(2),(3),(4),(5),(6),(7),(8),(9),(11),(12),(13),(14),(15),(17),(18)

this returns 16, but not 10. Example on SQL Fiddle .这将返回 16,但不是 10。 SQL Fiddle上的示例。

I think this is very similar to this question , but the minimum criteria is new.我认为这与这个问题非常相似,但最低标准是新的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM