One database problem-find the smallest positive integer missing from the keycol column in table T1
Source: Internet
Author: User
Insert into DBO. t1 (keycol, datacol) values (4, 'B'); insert into DBO. t1 (keycol, datacol) values (6, 'C'); insert into DBO. t1 (keycol, datacol) values (7, 'D'); -- looking for the minimum missing integer for DBO. t1 keycol columnselect casewhen not exists (select * From DBO. t1 with (nolock) Where keycol = 1) then 1 else (select Min (1 +. keycol) from DBO. t1 as a with (nolock) where not exists (select * From DBO. t1 as B with (nolock) where. keycol + 1 = B. keycol) end; select Min (. keycol + 1) from DBO. t1 as
Left Outer Join DBO. T1 as B
On B. keycol =. keycol + 1 where B. keycol is null; declare @ min int, @ Max intset @ min = 1 select @ max = max (keycol) + 1 from DBO. t1 (nolock) print @ minprint @ maxwhile (@ min <@ max) begin; if not exists (select * From DBO. t1 (nolock) Where keycol = @ min) begin; print @ min; break; end; elseset @ min = @ min + 1end;
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service