This little handy algorithm provides a truth table for any range of numbers between 0 and 65535 of any base between 2 and 36!As a twist, you can either return the digits concatenated or as separate columns.CREATE PROCEDURE dbo.uspTruthTable( @FromNumber SMALLINT = 0, @ToNumber INT = 255, @Step INT = 1, @Base TINYINT = 2, @Concat BIT = 0)ASSET NOCOUNT ONDECLARE @Temp INT, @SQL VARCHAR(8000), @b VARCHAR(12), @d VARCHAR(2), @Diff INT, @Digits CHAR(36)IF @FromNumber > @ToNumber SELECT @Temp = @FromNumber, @FromNumber = @ToNumber, @ToNumber = @TempIF @FromNumber < 0 BEGIN RAISERROR('The parameter FromNumber %d is less than 0 (base 10).', 16, 1, @FromNumber) RETURN ENDIF @ToNumber > 65535 BEGIN RAISERROR('The parameter ToNumber %d is greater than 65535 (base 10).', 16, 1, @ToNumber) RETURN ENDIF @Base < 2 BEGIN RAISERROR('The parameter Base %d is less than 2 (base 10).', 16, 1, @Base) RETURN ENDIF @Base > 36 BEGIN RAISERROR('The parameter Base %d is greater than 36 (base 10).', 16, 1, @Base) RETURN ENDSELECT @SQL = '', @Temp = FLOOR(LOG(@ToNumber) / LOG(@Base)), @Diff = @ToNumber - @FromNumber + 1, @Digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'WHILE @Temp >=0 SELECT @b = CONVERT(VARCHAR, @Base), @d = CONVERT(VARCHAR, @Temp), @SQL = @SQL + CASE WHEN @Concat = 1 THEN '+SUBSTRING(''' + @Digits + ''',1 + Number/POWER(' + @b + ',' + @d + ') % ' + @b + ', 1)' ELSE ',SUBSTRING(''' + @Digits + ''',1 + Number/POWER(' + @b + ',' + @d + ') % ' + @b + ', 1) AS Digit' + @d END, @Temp = @Temp - 1CREATE TABLE #Numbers ( Number INT PRIMARY KEY )INSERT #Numbers ( Number )VALUES ( @FromNumber )WHILE @Step <= @Diff BEGIN INSERT #Numbers SELECT @Step + Number FROM #Numbers WHERE Number <= @ToNumber - @Step SET @Step = @Step * 2 ENDIF @Concat = 1 SET @SQL = 'SELECT Number, ''''' + @SQL + ' AS Digits FROM #Numbers ORDER BY Number'ELSE SET @SQL = 'SELECT Number' + @SQL + ' FROM #Numbers ORDER BY Number'EXEC (@SQL)DROP TABLE #Numbers
You can use the algorithm like these examplesEXEC dbo.uspTruthTableEXEC dbo.uspTruthTable 0, 255, 1, 8EXEC dbo.uspTruthTable DEFAULT, 15, 1, 2
E 12°55'05.76"N 56°04'39.42"