Click here to Skip to main content
15,911,646 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to display the records which are missing in the table, with out using other table. Like using the self join.
Ex:
Table A
1
2
3
5
6
8
10
above table shows that there are missing numbers.
I want to display those missing numbers. That too with out using any other table.
Therefore the result shall display as:
Table A
4
7
9


Thanks in advance :)
Posted

1 solution

Try this:
SQL
;WITH CTE AS
(
  SELECT 1 AS FirstNo, MAX(MyNumber) AS LastNo
  FROM A
  UNION ALL
  SELECT FirstNo +1 As FirstNo, LastNo
  FROM CTE 
  WHERE FirstNo<LastNo
)
  SELECT FirstNo AS MyNumber
  FROM CTE
  EXCEPT 
  SELECT MyNumber
  FROM A
  OPTION (MAXRECURSION 0)


SqlFiddle

For further information, please see:
WITH common_table_expression (Transact-SQL)[^]
EXCEPT and INTERSECT (Transact-SQL)[^]

Linq solution:
C#
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("ID", Type.GetType("System.Int32"));
dt.Columns.Add(dc);
dt.Rows.Add(1);
dt.Rows.Add(2);
dt.Rows.Add(3);
dt.Rows.Add(5);
dt.Rows.Add(6);
dt.Rows.Add(8);
dt.Rows.Add(10);

int maxid = dt.AsEnumerable().Max(x=>x.Field<int>("ID"));

var qry = Enumerable.Range(1, maxid).Except(dt.AsEnumerable().Select(x=>x.Field<int>("ID")));
foreach(var n in qry)
{
    Console.WriteLine("{0}", n);
}
 
Share this answer
 
v4
Comments
Sascha Lefèvre 28-Mar-15 12:42pm    
+5! Copied to my SQL-snippet-collection :)
Maciej Los 28-Mar-15 12:43pm    
Thank you, Sascha ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900