Thursday, February 16, 2012

CROSS JOIN query with a TRUE/FALSE values

I am using SQL Server. Having two tables
Table T1:
ID Name
--
1 A
2 B
Table T2:
ID Description
--
1 a
2 b
SELECT * FROM T1, T2 gives:
1 A 1 a
1 A 1 b
2 B 1 a
2 B 2 b
========================================
===================
Question:
How to apply additional column (of a type bit) that would cross join
original query by combinations TRUE / FALSE, resulting something like
this:
1 A 1 a TRUE
1 A 1 b TRUE
2 B 1 a TRUE
2 B 2 b TRUE
1 A 1 a FALSE
1 A 1 b FALSE
2 B 1 a FALSE
2 B 2 b FALSE
Was thinking about creating a temporary table. But hoping for any
single query solutions. Thanks for your time, Boris.In fact there are no TRUE/FALSE values in SQL Server because it doesn't have
an explicit Boolean datatype you can use in columns. BIT is a numeric type
but conventionally developers often use it to represent TRUE and FALSE. I
think this may be the answer you are looking for:
SELECT *
FROM T1, T2,
(SELECT CAST(0 AS BIT) UNION ALL
SELECT CAST(1 AS BIT)) AS T(b) ;
David Portas
SQL Server MVP
--
"rubberbong@.yahoo.co.uk" wrote:

> I am using SQL Server. Having two tables
> Table T1:
> ID Name
> --
> 1 A
> 2 B
> Table T2:
> ID Description
> --
> 1 a
> 2 b
>
> SELECT * FROM T1, T2 gives:
> 1 A 1 a
> 1 A 1 b
> 2 B 1 a
> 2 B 2 b
> ========================================
===================
> Question:
> How to apply additional column (of a type bit) that would cross join
> original query by combinations TRUE / FALSE, resulting something like
> this:
> 1 A 1 a TRUE
> 1 A 1 b TRUE
> 2 B 1 a TRUE
> 2 B 2 b TRUE
> 1 A 1 a FALSE
> 1 A 1 b FALSE
> 2 B 1 a FALSE
> 2 B 2 b FALSE
> Was thinking about creating a temporary table. But hoping for any
> single query solutions. Thanks for your time, Boris.
>|||Pl try code below
create table #t1 (id int, Name varchar(1))
insert into #t1 values (1, 'A')
insert into #t1 values (2, 'B')
create table #t2 (id int, Name varchar(1))
insert into #t2 values (1, 'a')
insert into #t2 values (2, 'b')
select * from #t1, #t2,
(
select [col] from
(
select 'TRUE' [col]
union all
SELECT 'FALSE'
) a
) a
drop table #t1
drop table #t2
Rakesh
"rubberbong@.yahoo.co.uk" wrote:

> I am using SQL Server. Having two tables
> Table T1:
> ID Name
> --
> 1 A
> 2 B
> Table T2:
> ID Description
> --
> 1 a
> 2 b
>
> SELECT * FROM T1, T2 gives:
> 1 A 1 a
> 1 A 1 b
> 2 B 1 a
> 2 B 2 b
> ========================================
===================
> Question:
> How to apply additional column (of a type bit) that would cross join
> original query by combinations TRUE / FALSE, resulting something like
> this:
> 1 A 1 a TRUE
> 1 A 1 b TRUE
> 2 B 1 a TRUE
> 2 B 2 b TRUE
> 1 A 1 a FALSE
> 1 A 1 b FALSE
> 2 B 1 a FALSE
> 2 B 2 b FALSE
> Was thinking about creating a temporary table. But hoping for any
> single query solutions. Thanks for your time, Boris.
>

No comments:

Post a Comment