Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

How to generate combinations of values in SQL Server?

Total Hit ( 1549)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


Demonstrates the application of the CUBE operator for SELECT statement.

Click here to copy the following block
/*
    A temporary table is used to store the values for which the
    combinations have to be generated.
    Using a derived table in gives incorrect results & hence
    the workaround.
*/

declare @Value1 char( 1 ) , @Value2 char( 1 ) , @Value3 char( 1 ) , @Value4 char( 1 )
select @Value1 = 'a' , @Value2 = 'b' , @Value3 = 'c' , @Value4 = 'd'
create table #l (
    c1 char( 1 ) , c2 char( 1 ) , c3 char( 1 ) , c4 char( 1 )
);
insert #l values( @Value1 , @Value2 , @Value3 , @Value4 );
go
select coalesce( c1 , '' ) + coalesce( c2 , '' ) +
    coalesce( c3 , '' ) + coalesce( c4 , '' ) AS Combtn
from (
    select c1 , c2 , c3 , c4
    from #l
    group by c1 , c2 , c3 , c4
    with cube
) as t
where coalesce( c1 , c2, c3, c4 ) is not null
order by Combtn;
-- Expected Output:
/*
Combtn
------
a
ab
abc
abcd
abd
ac
acd
ad
b
bc
bcd
bd
c
cd
d
*/

go
drop table #l;

-- SQL2000 Only:
-- The derived table approach for completeness using the values directly
select coalesce( c1 , '' ) + coalesce( c2 , '' ) +
    coalesce( c3 , '' ) + coalesce( c4 , '' ) AS Combtn
from (
    select c1 , c2 , c3 , c4
    from (
        select 'a' , 'b' , 'c' , 'd'
    ) As c( c1 , c2 , c3 , c4 )
    group by c1 , c2 , c3 , c4
    with cube
) as t
where coalesce( c1 , c2, c3, c4 ) is not null;
go


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.