SQLUSA.com
SQL SERVER 2008 GRAND SLAM
FREE TRIAL  CLICK HERE TO ORDER  SEARCH
SQL JOBS SQL Server Training Scripts JOB BANK
  SQL Server 2008 Training Scripts  
  SQL Server 2005 Training Scripts  
News SQL Server Articles SQL Format

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

*/

 

Order SQL 2008 GRAND SLAM Today!
SQLUSA.com Home Page
SQL Server Training at www.sqlusa.com.
SQL Server 2008 Video Training at www.sqlusa.com.
SQL Server 2005 Training Videos at www.sqlusa.com.
Microsoft SQL Server 2000 Training Videos at www.sqlusa.com.

FREE SQL & Business Intelligence / OLAP Short Videos on YOUTUBE.com

Microsoft Community Contributor 2011
Invest in Your SUCCESS!

Search SQLUSA FREE SQL Server Articles & FREE T-SQL Scripts


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

SQL Server 2012 is a program product of Microsoft Corporation.
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.