Replace One Word or Phrase Through An Update Query

UPDATE queries are great to modify all information stored within our column. But what if we needed to only update a specific phrase or word within our column?

Well, we can use an UPDATE query along with a REPLACE function. It can be used like this:

UPDATE <table_name>
SET <column_name> = Replace(<column_name>, 'old phrase', 'new phrase')

What's The Difference Between NULL and DBNull

I always used NULL and DBNULL interchangeably in my coding around my database results without ever considering what were the differences. Fortunately, I stumbled upon a great blog written by Bilal Haidar, "Difference between NULL and DBNull"

If I understand correctly, you use DBNULL to check if a certain field in a database is null and you would use NULL to check if a whole record is not found in the database.

&quot;Timeout expired&quot; in SQL Server 2005

If you are running a query that needs to make changes to quite a few rows within a database (in my case 8700 rows). You might get an error exception pop up which says the following:

"Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding."

After some investigating I found that there are two ways to overcome this error:

1) Use Database Engine Query (or formally known as Query Analyser) to run your query instead of using SQL Panel in table view. I think that the SQL Query panel within table view is only used for smaller query operations. Thats just my guess because it didn't work for me. When using Database Engine query there is pretty much no limit to the amount of data you need.

2) Override connection timeout in SQL Server Options:


I found an option to change the timeout limit in the least place I expected. Under the "Designers" selection within SQL Server Options you will be able to change the timeout amount. But you cannot uncheck the override amount, you will have to specify the amount of seconds you require. 

ASP.NET Login Authentication Problem

I was trying to create a Login page for my website in ASP.NET a couple of days ago and I was stumped that the following piece of code did not work:

private bool SiteLevelCustomAuthenticationMethod(string User, string Password)
{   
   bool boolReturnValue = false;
   DataTable dtAuthUsers = SomeBLL.GetUsers();
   if (dtAuthUsers != null && dtAuthUsers.Rows.Count > 0)
   {
       DataView dvAuthUsers = dtAuthUsers.DefaultView;
       foreach (DataRowView drvAuthUsers in dvAuthUsers)
       {
            if (User == drvAuthUsers.Row["User"].ToString() && Password == drvAuthUsers.Row["Password"].ToString())
            {
                boolReturnValue = true;
            }
        }
    }
    return boolReturnValue;
}

protected void LoginControl_Authenticate(object sender, AuthenticateEventArgs e)
{
    bool Authenticated = false;
    Authenticated = SiteLevelCustomAuthenticationMethod(LoginControl.UserName, LoginControl.Password);
    e.Authenticated = Authenticated;
    if (Authenticated == true)
    {
        FormsAuthentication.RedirectFromLoginPage(string.Format("{0}", LoginControl.UserName), false);
    }
} 

Now after numerous debug sessions on this code, I could not find a thing wrong with it. The correct Username and Password was getting parsed to the Database but still the 'SiteLevelCustomAuthenticationMethod' function was still returning a false.

What was causing this problem was actually quite simple (even though it had taken my a long time to solve!). Basically, in the User's table in my database had the following columns:

1) User_ID ------> DataType: int
2) Username ------> DataType: nvarchar
3) Password ------> DataType: char

Now this table look alright doesn't it? Well it isn't. The problem lies within the 'Password' column. Since this column format is 'char' with a length of 25, when you enter a password that is less than 25 characters in length a space will be added after to fill out the data length. For example, if you had a password that was 10 characters long, an extra 15 characters of spacing will be added after your password.

In order to fix this problem, I changed the Password DataType to 'nvarchar', which solved the problem. 

UNION ALL

The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type.

One of my work colleagues at work showed me something that I never knew about UNION SQL statement. By default the UNION statement does the exact same thing as a SELECT DISTINCT on the resulting data. But what if we want to carry out a UNION without distincting the data result? Thats where the UNION ALL comes into play.

Example

Table 1: tblCars-UK 

Car_ID Car_Name
1 Volvo
2 Volkswagen
3 Chevrolet
4 Nissan
5 BMW

Table 2: tblCars-US

Car_ID Car_Name
1 Pontiac
2 Chrysler
3 Chevrolet
4 Dodge
5 BMW

If we used a UNION statement, the results would be as follows:

Select car_name from tblCars-UK
UNION
Select car_name from tbleCars-US 

Car_Name
Volvo
Volkswagen
Chevrolet
Nissan
BMW
Pontiac
Chrysler
Dodge

As you can see from the results above that the duplicate car entries have been removed and only displayed once. Now this is what will happen if we use UNION ALL statement:

Select car_name from tblCars-UK
UNION ALL
Select car_name from tbleCars-US


Car_Name
Volvo
Volkswagen
Chevrolet
Nissan
BMW
Pontiac
Chrysler
Chevrolet
Dodge
BMW

Implement SCOPE_IDENTITY() in Data Access Layer

The SCOPE_IDENTITY() function are used in Insert queries to return the last identity value within your table. However, I never knew how to retrieve the ID value when using this function in my code.

Create an Insert Query in your Data Access Layer called "InsertUser". For example: 

INSERT INTO Users (FirstName, LastName, DateOfBirth, Email, City) VALUES (@FirstName, @LastName, @DateOfBirth, @Email, @City);
SELECT SCOPE_IDENTITY() 

When you return to the DataSet Designer you'll see that the "InsertUser" method has been created. If this new method doesn't have a parameter for each column in the table, chances are you forgot to terminate the INSERT statement with a semi-colon. Configure the "InsertUser" method and ensure you have a semi-colon delimiting the INSERT and SELECT statements.

By default, insert methods issue non-query methods, meaning that they return the number of affected rows. However, we want the "InsertUser" method to return the value returned by the query, not the number of rows affected. To accomplish this, adjust the "InsertUser" method's ExecuteMode property to Scalar (this can be found in the Properties panel on the right).

The following code will put your new Insert Query into action: 

int intUserID = Convert.ToInt32(BLL.InsertUser("John", "Doe", "16/06/1985", "joe@hotmail.com", "Oxford"));
//Output new User ID
Response.Write("New User ID Inserted: " + intUserID); 

For more info regarding the use of Data Access in ASP.NET 2.0 go to: http://msdn2.microsoft.com/en-us/library/Aa581778.aspx

About

Surinder Bhomra is a Web Developer.

He has achieved a BSc in Information Systems in 2006 and since then has been working in the IT industry.

Prior to working in the Web Development industry I have spent 1.5 years working as an IT Systems Analyst providing support for internal company systems.

Working in the Web Development industry has given me the opportunity to expand my current skills and allowing me to work on website projects using ASP, ASP.NET, CSS, HTML and SQL.

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.

>