SQLUSA

Microsoft SQL Server 2005 Best Practices

How to use SQL CROSS JOIN in automatic sequence generation?

Execute the following script in Query Editor to demonstrate the architecture of an SQL query with CROSS JOIN. The SQL query with the CROSS JOIN produces a sequence of 31 numbers which used for running out the dates into the future:

 

use AdventureWorks

go

 

-- Create a cte to give the sequence of 1-9

with cteSequence

as

(select 0 SeqNo

union select 1

union select 2

union select 3

union select 4

union select 5

union select 6

union select 7

union select 8

union select 9)

 

select DayInMonth=dateadd(d,10*b.SeqNo+a.SeqNo,

       convert(varchar,getdate(),111))

from cteSequence a

cross join cteSequence b

where b.SeqNo < 4

and 10*b.SeqNo + a.SeqNo < 31

go

SQLUSA - The Best SQL Server Training in the World
 
 
SQLUSA.com Home Page