SQLUSA
FREE TRIAL  CLICK HERE TO ORDER  SEARCH
SQL Server 2008 Training Scripts
SQL Server 2005 Training Scripts
SQL Server Training Scripts
ORDER LINK FOR SQL 2008 GRAND SLAM
How to use SQL CROSS JOIN in automatic sequence generation?

Execute the following T-SQL example script in Query Editor to demonstrate the architecture of an SQL query with CROSS JOIN.

The SQL query with the SELF CROSS JOIN of a CTE produces a sequence of 31 numbers which are used for running out the dates into the future starting with today:

-- Generate sequence 0-99 with cross join of CTE - SQL sequence

-- SQL cross join - SQL date sequence

USE AdventureWorks

GO

 

-- Create a cte to give the sequence of digits (0-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)

-- Main query

-- SQL dateadd datetime function

SELECT DayInMonth = Dateadd(d,10 * b.SeqNo + a.SeqNo,Convert(VARCHAR,Getdate(),111))

-- SQL self cross join

FROM   cteSequence a

       CROSS JOIN cteSequence b

WHERE  b.SeqNo < 4

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

 

GO

/* Partial results

 

DayInMonth

2015-01-31 00:00:00.000

2015-02-01 00:00:00.000

2015-02-02 00:00:00.000

2015-02-03 00:00:00.000

2015-02-04 00:00:00.000

2015-02-05 00:00:00.000

2015-02-06 00:00:00.000

2015-02-07 00:00:00.000

*/

 

The World Leader in SQL Server 2008 Training
Order SQL 2008 GRAND SLAM Today!
The Future is just a CLICK away! Your Future!
SQLUSA.com Home Page

Copyright 2005-2010, SMI Corp. All Rights Reserved.

SQL Server 2008 is a program product of Microsoft Corporation.
SQL Server 2005 is a program product of Microsoft Corporation.
SQL Server 2000 is a program product of Microsoft Corporation.