Действительно, очень жестокий подход , для большинства СУБД это будет работать (кроме Oracle, где вам нужно select..from dual
). Это должно работать в DB2, даже если у вас нет доступа к созданию / обновлению таблиц и может только SELECT
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