Always Get Better

Archive for the ‘SQL’ Category

How to SUM Bit Fields in SQL

Sunday, April 6th, 2008

By default, SQL Server doesn’t allow an operation like this:

[source:sql]
SELECT SUM(blnBitColumn) FROM tblTable;
[/source]

In order to achieve this result, you must first convert the bit column to a numeric type:

[source:sql]
SELECT SUM(CONVERT(int,blnBitColumn)) FROM tblTable;
[/source]

This counts the number of times the bit is true.

If you want to get the flip-side of that to see how many times the bit is false, just subtract the total number of bits from the positive:

[source:sql]
SELECT COUNT(blnBitColumn)-SUM(CONVERT(int,blnBitColumn)) FROM tblTable;
[/source]

SQL Connections in ASP.NET – What you learned is WRONG!

Friday, February 15th, 2008

When we learn how to open and use a database connection with ASP.NET, as with any other programming concept in any other programming language, the simplified version used to explain what’s going on is not truly representative of the quality professional code we will one day be expected to write.
Opening and Closing Connections

Case in point: managing of sql database connection resources. How many of us learned to write something like this:


// Create a new SQL Connection object
SqlConnection conn = new SqlConnection( connectionString );

// Open the connection to the database
conn.Open();

// Create a new SQL Command
SqlCommand cmd = new SqlCommand( “DELETE FROM BabyNames;”, conn );

// Execute the command
cmd.ExecuteNonQuery();

// Close the database connection
conn.Close();

Sure it’s easy to follow, but if you deploy that on a moderately busy server you are going to make your client very unhappy.

Dispose Resources

SQLConnection and SQLCommand objects reference unmanaged resources, meaning the C# garbage collector has no framework knowledge about your object. Since these classes both implement the disposable interface it is important to call the Dispose() method in order to correctly free your application’s used memory.

So our code gets updated to look like this:


// Create a new SQL Connection object
SqlConnection conn = new SqlConnection( connectionString );

// Open the connection to the database
conn.Open();

// Create a new SQL Command
SqlCommand cmd = new SqlCommand( “DELETE FROM BabyNames;”, conn );

// Execute the command
cmd.ExecuteNonQuery();

// Dispose of the command
cmd.Dispose();

// Close the database connection
conn.Close();

// Dispose of the connection object
conn.Dispose();

Trap for Errors

What happens if there’s a problem, and your code fails to complete? If your application crashes before your objects are disposed, you are left with the same effect as if you had never disposed your objects at all!

Fortunately, C# includes the try … finally reserved words. If anything within the try { } block fails, the finally { } still executes. We can easily apply this to our program code:


// Create a new SQL Connection object
SqlConnection conn = new SqlConnection( connectionString );

try
{
// Open the connection to the database
conn.Open();

// Create a new SQL Command
SqlCommand cmd = new SqlCommand( “DELETE FROM BabyNames;”, conn );

try
{
// Execute the command
cmd.ExecuteNonQuery();
}
finally
{
// Dispose of the command
cmd.Dispose();
}

// Close the database connection
conn.Close();
}
finally
{
// Dispose of the connection object
conn.Dispose();
}

For my own part, I prefer the using keyword. We can include a using call anywhere we would ordinarily use a disposal object. When the code is compiled, it behaves the same as try … catch, but leaves our program code much more readable.

Even better, we don’t even have to bother calling Dispose() because it does it for us!


// Create a new SQL Connection object
using ( SqlConnection conn = new SqlConnection( connectionString ) )
{
// Open the connection to the database
conn.Open();

// Create a new SQL Command
using ( SqlCommand cmd = new SqlCommand( “DELETE FROM BabyNames;”, conn ) )
{
// Execute the command
cmd.ExecuteNonQuery();
}

// Close the database connection
conn.Close();
}

Slick.

Open Late, Close Early (like a bank)

There is one more thing I would add to this. Creating objects in memory takes time. Although it happens in fractions of a second too fast to be detectable by us, it’s important not to waste processing time wherever possible.

Whenever we Open() a database connection, we expect to use the database right away. If we then create an SqlCommand, we’re wasting the open connection’s time. It’s as if we pick up the phone and listen to the dial tone while we then flip through the white pages looking for the number we want to call.

Let’s change our example code so we will now Open() at the last possible opportunity, and Close() right away when we’ve made our call:


// Create a new SQL Connection object
using ( SqlConnection conn = new SqlConnection( connectionString ) )
{
// Create a new SQL Command
using ( SqlCommand cmd = new SqlCommand( “DELETE FROM BabyNames;”, conn ) )
{
// Open the connection to the database
conn.Open();

// Execute the command
cmd.ExecuteNonQuery();

// Close the connection to the database
conn.Close();
}
}

In the end, the program code we wrote is very similar to the newbie code we started with. However, we’re now protecting our system from memory leaks, and we’re protecting our database from wasted clock cycles. Our code is easy to read and stable.

How to Create Full Text Search Using mySQL

Thursday, February 14th, 2008

Search is one of the most basic features visitors expect when they come to a web site. This is especially true in e-commerce where your ability to make a sale is directly related to your customer’s ability to find the product they’re looking for.

Using Third-Party Solutions

Many first-time site owner choose to go with Google Custom Search because of its easy setup and because of Google’s incredible indexing reach and results. I don’t like the standard edition of the Custom Search because of the branding – your search results advertise Google and provide links to competing content. For an e-commerce site to lose control of such a critical function, the results can be costly.

Don’t Give Up Control

Especially in e-commerce, it is best to never give up control over any content. Advanced users may choose to ignore your site’s search tool and use Google to get at your content anyway (via the site: directive) but in the general case there is great potential to keep selling useful products to your potential customers even while they search your site for other items.

Incorporating a decent search tool into a web site using PHP is dead simple. All it involves is a database table with 3 or more rows and a little bit of an eye for layout. Even if you don’t consider yourself a designer, having a look around other search engines will give you a feel for how results should display.

Creating the Search Tables

Let’s get started. Our simplistic database table (PRODUCTS) will consist of the following columns:

Column Name Data Type Description
intID int Product ID and Primary Key
vcrName varchar(25) Product Name
txtDescription text Product Description
vcrPhoto varchar(40) Path (URL) to product photo

Obviously this is just a simplified example, but the product ID, name, description and photo should be enough for the purposes of our demonstration.

The SQL to create the table looks like this:
[source:sql]
CREATE TABLE PRODUCTS
(
intID int auto_increment,
vcrName varchar(25),
txtDescription text,
vcrPhoto varchar(40),
CONSTRAINT PRODUCTS_pk PRIMARY KEY ( intID )
);
[/source]

Add the Full-Text Index

In this example, we’re interested in searching the name and description fields of our products. In order to add the full-text index to our table, we use the ALTER TABLE command:

[source:sql]
ALTER TABLE PRODUCTS ADD FULLTEXT( vcrName, txtDescription );
[/source]

Alternatively, we could have created the index along with the table in our original CREATE statement like this:

[source:sql]
CREATE TABLE PRODUCTS
(
intID int auto_increment,
vcrName varchar(25),
txtDescription text,
vcrPhoto varchar(40),
CONSTRAINT PRODUCTS_pk PRIMARY KEY ( intID ),
FULLTEXT( vcrName, txtDescription )
);
[/source]

Searching For Text

Now that the index has been created, we can go ahead and search the database. To activate full-text search, we use the MATCH () AGAINST () syntax like this:

[source:sql]
SELECT intID, vcrName, txtDescription, vcrPhoto
FROM PRODUCTS
WHERE MATCH( vcrName, txtDescription ) AGAINST ( ‘search terms here’ );
[/source]

That’s all there is to it! Anyone with access to a mySQL database should be able to incorporate search into their sites without too much difficulty. Of course this is a very basic introduction, but should be more the sufficient to get going with.