SQL SERVER – Binary Sequence Generator – Truth Table Generator

Run following script in query editor to generate truth table with its decimal value and binary sequence. The truth table is 512 rows long. This can be extended or reduced by adding or removing cross joins respectively.

Script:
USE AdventureWorks;
DECLARE @Binary TABLE ( Digit bit)
INSERT @Binary
VALUES (0)
INSERT @Binary
VALUES (1)
SELECT ((a.Digit*256) + (b.Digit*128) + (c.Digit*64) +
(
d.Digit*32) + (e.Digit*16) + (f.Digit*8) +
(
g.Digit*4) + (h.Digit*2) + (i.Digit*1)) DecimalValue,
a.Digit '256', b.Digit '128' , c.Digit '64',
d.Digit '32', e.Digit '16', f.Digit '8',
g.Digit '4', h.Digit '2', i.Digit '1'
FROM @Binary a
CROSS JOIN @Binary b
CROSS JOIN @Binary c
CROSS JOIN @Binary d
CROSS JOIN @Binary e
CROSS JOIN @Binary f
CROSS JOIN @Binary g
CROSS JOIN @Binary h
CROSS JOIN @Binary i
ORDER BY ((a.Digit*256) + (b.Digit*128) + (c.Digit*64) +
(
d.Digit*32) + (e.Digit*16) + (f.Digit*8) +
(
g.Digit*4) + (h.Digit*2) + (i.Digit*1))
GO

Resultset:
DecimalValue 256 128 64 32 16 8 4 2 1
———— —– —– —– —– —– —– —– —– —–
0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 1
2 0 0 0 0 0 0 0 1 0
3 0 0 0 0 0 0 0 1 1
4 0 0 0 0 0 0 1 0 0
5 0 0 0 0 0 0 1 0 1
6 0 0 0 0 0 0 1 1 0
7 0 0 0 0 0 0 1 1 1
8 0 0 0 0 0 1 0 0 0
9 0 0 0 0 0 1 0 0 1
10 0 0 0 0 0 1 0 1 0
11 0 0 0 0 0 1 0 1 1
12 0 0 0 0 0 1 1 0 0
13 0 0 0 0 0 1 1 0 1
14 0 0 0 0 0 1 1 1 0
15 0 0 0 0 0 1 1 1 1
16 0 0 0 0 1 0 0 0 0
—- many rows —-
509 1 1 1 1 1 1 1 0 1
510 1 1 1 1 1 1 1 1 0
511 1 1 1 1 1 1 1 1 1

(512 row(s) affected)
Reference : Pinal Dave (http://blog.SQLAuthority.com)

About these ads

One thought on “SQL SERVER – Binary Sequence Generator – Truth Table Generator

  1. Pingback: SQL SERVER – Weekly Series – Memory Lane – #029 | SQL Server Journey with SQL Authority

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s