C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




Find the missing numbers (GAPS) within a table...


Posted Date: 02 May 2007    Resource Type: Code Snippets    Category: SQL

Posted By: Vadivel Mohanakrishnan       Member Level: Diamond
Rating:     Points: 10



In this post I have given one of the way to find out the missing numbers within a table. Please note that you need SQL Server 2005 to execute this example and test it yourself.

Sample table creation:



Create table tblFindGaps
(
Sno int not null
)
Go



Populate dummy records in the table:



Insert tblFindGaps values (1)
Insert tblFindGaps values (10)
Insert tblFindGaps values (3)
Insert tblFindGaps values (5)
Insert tblFindGaps values (9)
Insert tblFindGaps values (11)
Insert tblFindGaps values (15)
Insert tblFindGaps values (18)
Insert tblFindGaps values (22)
Insert tblFindGaps values (100)
Go



Solution to find the missed out numbers:



Declare @intMaxNum int
Select @intMaxNum = max(Sno) from tblFindGaps;

With tempData (result) as
(
Select distinct FG.Sno + 1 from tblFindGaps FG where not exists
(
Select 1 from tblFindGaps FGP where FGP.Sno = FG.Sno + 1
) and FG.Sno < @intMaxNum

Union All

Select TD.result + 1 from tempData TD where not exists
(
Select 1 from tblFindGaps FGP where FGP.Sno = TD.result + 1
) and TD.result < @intMaxNum
)
Select result as 'Missing Numbers' from tempData order by result;





Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Read the status of SQL Server Agent jobs
Previous Resource: GRANT permission to ALL stored procedures
Return to Discussion Resource Index
Post New Resource
Category: SQL


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design

online optimum rewards

Contact Us    Privacy Policy    Terms Of Use