SQLUSA.com
SQL SERVER 2008 GRAND SLAM
FREE TRIAL  CLICK HERE TO ORDER  SEARCH
SQL JOBS SQL Server Training Scripts JOB BANK
  SQL Server 2008 Training Scripts  
  SQL Server 2005 Training Scripts  
News SQL Server Articles SQL Format

 


Binary Pattern Display in T-SQL

By Kalman Toth, M.Phil. Physics, M.Phil. Computing Science, MCDBA, MCITP

May 1, 2011

Software engineers don't think of Transact-SQL as a serious language like C++. More in the lightweight category with excellent sql query capacity, manipulating millions of rows at ease. While you cannot do object-oriented programming in T-SQL, you can now in SQL 2005 parse trees with recursive CTEs as an example for advancement in T-SQL. You don't really want to do heavy-duty algorithmic programming in T-SQL anyhow, since it is an interpreted language. If you resort to Java-like programming, make sure the stored procedure or function is not used frequently since inline coding performs better. Below is a sample function to illustrate the tremendous flexibility of the T-SQL language. Bit-wise Boolean operators are used to produce a bit switch display of byte.

Following is the code sample:

USE AdventureWorks

GO

 

CREATE FUNCTION dbo.fnBinaryPattern

               (@Byte TINYINT)

RETURNS CHAR(8)

AS

  BEGIN

    DECLARE  @Pattern CHAR(8)

    

    SET @Pattern = ''

    

    SELECT @Pattern = convert(VARCHAR,+(@Byte & 1) / 1) +

    convert(VARCHAR,(@Byte & 2) / 2) +

    convert(VARCHAR,(@Byte & 4) / 4) +

    convert(VARCHAR,(@Byte & 8) / 8) +

    convert(VARCHAR,(@Byte & 16) / 16) +

    convert(VARCHAR,(@Byte & 32) / 32) +

    convert(VARCHAR,(@Byte & 64) / 64) +

    convert(VARCHAR,(@Byte & 128) / 128)

    

    RETURN reverse(@Pattern)

  END

GO 

select dbo.fnBinaryPattern(0)
go

00000000

select dbo.fnBinaryPattern(1)
go

00000001

select dbo.fnBinaryPattern(128)
go

10000000

select dbo.fnBinaryPattern(ascii('B'))
go

01000010

select dbo.fnBinaryPattern(ascii('b'))
go

01100010

Related articles:

Bit-Masks

How to use the Boolean / bit data type?

Speed Up Performance And Slash Your Table Size By 90% By Using Bitwise Logic

 


Order SQL 2008 GRAND SLAM Today!
SQLUSA.com Home Page
SQL Server Training at www.sqlusa.com.
SQL Server 2008 Video Training at www.sqlusa.com.
SQL Server 2005 Training Videos at www.sqlusa.com.
Microsoft SQL Server 2000 Training Videos at www.sqlusa.com.

FREE SQL & Business Intelligence / OLAP Short Videos on YOUTUBE.com

Microsoft Community Contributor 2011
Invest in Your SUCCESS!

Search SQLUSA FREE SQL Server Articles & FREE T-SQL Scripts


Copyright 2005-2011, SMI Corp. All Rights Reserved.

SQL Server 2012 is a program product of Microsoft Corporation.
SQL Server 2008 is a program product of Microsoft Corporation.
SQL Server 2005 is a program product of Microsoft Corporation.
SQL Server 2000 is a program product of Microsoft Corporation.