真正残酷的方法,对于大多数 DBMS,这将起作用(Oracle 除外,您需要 select..from dual)。即使您无权创建/更新表并且只能SELECT
,这也应该适用于 DB2
select N1.N * 1000 + N2.N * 100 + N3.N * 10 + N4.N as NonExistentCustomerID
from (
select 1 as N union all select 2 union all select 3 union all
select 4 union all select 5 union all select 6 union all
select 7 union all select 8 union all select 9 union all
select 0) N1
cross join (
select 1 as N union all select 2 union all select 3 union all
select 4 union all select 5 union all select 6 union all
select 7 union all select 8 union all select 9 union all
select 0) N2
cross join (
select 1 as N union all select 2 union all select 3 union all
select 4 union all select 5 union all select 6 union all
select 7 union all select 8 union all select 9 union all
select 0) N3
cross join (
select 1 as N union all select 2 union all select 3 union all
select 4 union all select 5 union all select 6 union all
select 7 union all select 8 union all select 9 union all
select 0) N4
where N1.N * 1000 + N2.N * 100 + N3.N * 10 + N4.N in (1,2,3)
and not exists (
select * from customer c where c.customerid = v.number + v2.number*1000)
根据需要扩展子查询以覆盖整个数字范围。
如果您可以创建表格(或有一个方便的),请创建一个“数字”表格,而不是使用数字 0 到 9(10 条记录),并继续加入自身,即
create table Numbers (N int)
insert into Numbers
select 1 union all select 2 union all select 3 union all
select 4 union all select 5 union all select 6 union all
select 7 union all select 8 union all select 9 union all
select 0
select N1.N * 1000 + N2.N * 100 + N3.N * 10 + N4.N as NonExistentCustomerID
from numbers N1
cross join numbers N2
cross join numbers N3
cross join numbers N4
where N1.N * 1000 + N2.N * 100 + N3.N * 10 + N4.N in (1,2,3)
and not exists (
select * from customer c where c.customerid = v.number + v2.number*1000)
numbers 表对于各种查询总是有用的。
供 SQL Server 参考,假设数字在 0-2047 范围内,您可以使用
select v.number
from master..spt_values v
left join customer c on c.customerid = v.number
where v.type='P' and v.number in (1,2,3)
and v.customerid is null
如果您需要更大的范围,请继续加入 master..spt_values 以获得更大的范围
select v.number + v2.number*1000 as NonExistentCustomerID
from master..spt_values v
inner join master..spt_values v2 on v2.type='P'
where v.type='P' and v.number + v2.number*1000 in (1,2,3)
and v.number between 0 and 999
and not exists (
select * from customer c where c.customerid = v.number + v2.number*1000)
order by 1