Sql server 找到不存在的值的最佳方法

Sql server 找到不存在的值的最佳方法,sql-server,Sql Server,我们有一个mssql表System.dbo.DirectMapping,它有一个字段、帐户。不确定你是否看到了我的另一个问题,但它们不是唯一的。在我询问获取现有帐户的最佳方式之前。现在我需要找到一个不存在的。我读到了一种生成从1到1000的数字的方法,所以我的策略是在该范围内找到一个不在DirectMapping表中的数字。这是可行的,但很麻烦。我不知道有没有更方便的方法 SELECT num from ( SELECT ones.n + 10*tens.n + 100*hundreds.n +

我们有一个mssql表System.dbo.DirectMapping,它有一个字段、帐户。不确定你是否看到了我的另一个问题,但它们不是唯一的。在我询问获取现有帐户的最佳方式之前。现在我需要找到一个不存在的。我读到了一种生成从1到1000的数字的方法,所以我的策略是在该范围内找到一个不在DirectMapping表中的数字。这是可行的,但很麻烦。我不知道有没有更方便的方法

SELECT num from (
SELECT ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n as num
FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),
 (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) tens(n),
 (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) hundreds(n),
 (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) thousands(n)) j
where j.num not in (select account from System.dbo.DirectMapping)

假设account是数字,上面的查询将始终返回一个不存在的值

这应该可以帮到您

with a as (
select  row_number() over(order by account) as rownum from System.dbo.DirectMapping)
select * from a
where rownum not in (select account from System.dbo.DirectMapping) and rownum <1000

一旦您使用了帐户中所有小于1000的数字,就可以替换

a.rownum <1000

或者您要检查的任何其他范围

如果有人来这里试图在甲骨文中这样做,那就更简单了

    select rownum from System.dbo.DirectMapping 
where rownum <1000 and rownum not in (select account from System.dbo.DirectMapping)

如果我理解你的问题

假设AccountID是一个INT,并且您希望查找缺少的ID或间隙

范例

返回缺少的AccountID

另一个答案是:

创建一个表accounts_temp,该表只有一列,其中包含DirectMapping表中account列中预期包含的所有数字,并使用该表查找缺少的数字

select min(account) from accounts_temp where account not in (
select account from System.dbo.DirectMapping)

您只是在数据库中寻找一个唯一的数字来分配给新行吗?您的最终目标是什么?您当前的轨迹似乎很奇怪。是的,我必须输入一个表单,并获得未找到的结果帐户。所以我需要找到一个不存在的帐户。你能给我解释一下这是如何回答这个问题的吗?查询将始终返回一个不存在的值。例如,如果maxaccount返回10,则11不存在,否则maxaccount将返回11。假设帐户是数字的。抱歉,我指的是扩大你的答案,以包括额外的信息,因为在审查队列中出现的答案是短的。一般来说,除了代码外,SO更喜欢有解释的答案。
 a.rownum >=1000 and  a.rownum <2000 
    select rownum from System.dbo.DirectMapping 
where rownum <1000 and rownum not in (select account from System.dbo.DirectMapping)
Declare @YourTable table (AccountID int)
Insert Into @YourTable values
(1),(1),(5),(6),(7),(8),(9)   -- Notice 2,3,4 are missing in non-distinct list

Select MissingIDs = A.N
 From (
        Select Top (Select max(AccountID) from @YourTable) N=Row_Number() Over (Order By (select null)) 
        From  master..spt_values n1,master..spt_values n2
      ) A
 Left Join @YourTable B  on A.N=B.AccountID
 Where B.AccountID is null
MissingIDs
2
3
4
select min(account) from accounts_temp where account not in (
select account from System.dbo.DirectMapping)