|
-
Mar 25th, 2009, 05:41 PM
#1
[RESOLVED] DB (Access or SQL Server) - Using pure SQL find first available Key in Table
How to get the first Key available in a given Table, assumming some entries has been deleted, there are gaps, i need an SQL Query to get the first available, examples:
1, 2, 3, 6, 7, 8, 10, 14, 15
(it should return 4)
6, 7, 8, 10, 14, 15
(it should return 1)
I did this one, but there is a problem, this query returns the Key available after the first gap, not before..
Code:
SELECT MIN(a.CODE-1)
FROM Table AS a
LEFT JOIN Table AS b ON a.CODE - 1 = b.CODE
WHERE b.CODE IS NULL AND a.CODE <> 1;
Last edited by jcis; Mar 25th, 2009 at 05:48 PM.
-
Mar 25th, 2009, 06:30 PM
#2
Re: DB (Access or SQL Server) - Using pure SQL find first available Key in Table
I am not sure if this will work in Access but should work with SQL Server.
Code:
SELECT
CASE
WHEN MAX(code) = COUNT(*)
THEN CAST(NULL AS INTEGER)
WHEN MIN(code) > 1
THEN 1
WHEN MAX(code) <> COUNT(*)
THEN
(SELECT MIN(code) + 1
FROM [TABLE]
WHERE
(
code + 1
)
NOT IN
(SELECT code
FROM [TABLE]
)
)
ELSE NULL
END
FROM [TABLE]
-
Mar 25th, 2009, 06:36 PM
#3
Re: DB (Access or SQL Server) - Using pure SQL find first available Key in Table
Yes, that should work, i don't have SQL Server installed so i was testing with Access and i needed to add a SELECT CASE to do that but i don't know how to do it in Access, I'll install SQL Server now so I can test your code, thank you.
-
Mar 25th, 2009, 07:15 PM
#4
Re: DB (Access or SQL Server) - Using pure SQL find first available Key in Table
It works, thanks dee-U
-
Mar 26th, 2009, 02:13 AM
#5
Re: [RESOLVED] DB (Access or SQL Server) - Using pure SQL find first available Key in
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|