Click here to Skip to main content
15,913,854 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have Dates and Data Stored in table
as

1
3
8
9
assume above as date fields
I just Want to display
without leaving the gaps in between
1
2
3
4
5
6
7
---- and so on till the last Date Field
How can I achieve this.using sql
Posted
Updated 23-Apr-12 1:44am
v2

You can use WHILE[^] and DATEADD[^]

Psuedocode

WHILE( DATE < LastDate)
BEGIN
  IF EXISTS(SELECT DATE FROM table)
    CONTINUE
  ELSE
    DATEADD(day, 1, DATE)
END
 
Share this answer
 
You can use this also!!!!

SQL
 with GETDATES as
 (
   select cast(STARTDATE as datetime) DateValue
    union all
   select DateValue + 1
    from  GETDATES    where   DateValue + 1 < ENDDATE
) select DateValue  from   GETDATES
 OPTION (MAXRECURSION 0)
 
Share this answer
 
v2
Comments
[no name] 23-Apr-12 10:46am    
Only the code snippets need to be formatted. Not all of the text.
[no name] 23-Apr-12 10:48am    
CTE is only available in SQL Server 2005 and above. Since the OP did not specify which version was being used it should be noted in your solution.
Actually your question is not so clear but as my understanding if u want the list all the date fields like in your DB table date entry are 5,15,25.

Date fields return 5 to 25 in sequence.....

First got the startdate and lastdate then use the BELOW SQL FUNTION


SQL
CREATE FUNCTION dbo.GenerateDates(@startdate datetime, @enddate datetime)
returns table as
return (
with 
 N0 as (SELECT 1 as n UNION ALL SELECT 1)
,N1 as (SELECT 1 as n FROM N0 t1, N0 t2)
,N2 as (SELECT 1 as n FROM N1 t1, N1 t2)
,N3 as (SELECT 1 as n FROM N2 t1, N2 t2)
,N4 as (SELECT 1 as n FROM N3 t1, N3 t2)
,N5 as (SELECT 1 as n FROM N4 t1, N4 t2)
,N6 as (SELECT 1 as n FROM N5 t1, N5 t2)
,nums as (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as num FROM N6)
SELECT DATEADD(day,num-1,@startdate) as thedate
FROM nums
WHERE num <= DATEDIFF(day,@startdate,@enddate) + 1
);
 
Share this answer
 
v2
Comments
[no name] 23-Apr-12 10:45am    
Does not provide enough flexibility to be reusable

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