Microsoft, SQL, SQL Server, Technical

Query for Powers of 2 in SQL Server 2005

I had a table with two columns: ID and Description. The task was to display the description of all elements whose ID is a power of two. Here’s the query that let me accomplish that:

SELECT ID, Desc FROM tblBits WHERE ID > 0 AND ID & (ID-1) = 0

How does this work?

Every power of two when converted to binary has only one bit set.
For example: 4=100, 8=1000, 16=10000
And one digit less in binary looks like:
3 = 011, 7=0111, 15=01111

So an AND operation between {4,3}, {8,7}, {16,15} and so on will always yield a ‘0’

Code, Microsoft, Performance, SQL, SQL Server, T-SQL, Technical

Computed Columns in SQL Server 2005

“Computed Columns” as the name suggests allows you to set the value of a column based on other columns data. Here’s how you could specify the formula in T-SQL:

--Create Table
CREATE TABLE T1 (
    a INT, 
    b INT, 
    operator CHAR,
    c AS CASE operator
        WHEN '+' THEN a+b
        WHEN '-' THEN a-b
        ELSE a*b
    END
    PERSISTED
) ;

--Insert dummy data into it
INSERT INTO T1 VALUES(1,2,'+')
INSERT INTO T1 VALUES(5,3,'-')
INSERT INTO T1 VALUES(4,4,'')

--View the results
SELECT * FROM T1

Notice the keyword PERSISTED. This will enable the computed column value to be stored physically on to the disk so that it need not be created every time you ask for it. Creating an index on this computed column will improve performance by doing a seek rather than a table scan.

If you want to specify the above computed column in SQL Server management studio directly you can do this:

Modify the table. Go to the computed column specification for the specific column. Expand it and type the following in the “Formula” field:

(CASE [operator] WHEN '+' THEN [a]+[b] WHEN '-' THEN [a]-[b]

ELSE [a]*[b] END)

Enter without line breaks. If you want the column values to be persisted in the storage medium, just change the value of “Is Persisted” to “Yes”

SQL, SQL Server, T-SQL, Technical

Concatenating column values in SQL Server 2000/2005

If you want to concatenate values from a specific column like for example:

Table
=====
1    One
2    Two
3    Three
4    Four

to the following:

Output
======
One, Two, Three, Four

Here is a simple way to do it:

SQL Server 2005:

SELECT STUFF(SELECT ‘, ‘ + ColumnName FROM TableName FOR XML PATH(”),1,2,”)

SQL Server 2000:

DECLARE @t varchar(4000)
SET @t = ”
SELECT @t = @t + ‘, ‘ + ColumnName From TableName
SELECT STUFF(@t,1,2,”)

STUFF() deletes a specified length of characters and inserts another set of characters at a specified starting point.