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 (https://blog.sqlauthority.com)

SQL Function, SQL Scripts, SQL Utility
Previous Post
SQL SERVER – DBCC commands List – documented and undocumented
Next Post
SQL SERVER – Fix: Error 130: Cannot perform an aggregate function on an expression containing an aggregate or a subquery

Related Posts

Leave a Reply