Monday, 3 November 2008

Equals, Equals Equals or Equals Equals Equals?

In JavaScript, you often see conditional statements with 3 equals signs (===). I always thought it was a typo but it turns out to have a significant advantage over the traditional 2 equals signs (==). This post shows how to use 1, 2 or 3 equals signs effectively.


Assign and evaluate
 if ( x = y + z ) { alert( "true" ); }

Assigns x to the sum of y and z and evaluates the result.


Compare (irrespective of data type)
 if ( x == y + z ) { alert( "true" ); }

The result of the sum of y and z is compared to x where both sides must have the same value.

Example:
x = "5"
y = 10
z = -5

y + z = 5

Using the above values, the condition will be considered to be true because the sum of y and z is converted to a string prior to the comparison.


Compare and match data types
 if ( x === y + z ) { alert( "true" ); }

The result of the sum of y and z is compared to x where both sides must have the same value and be of the same data type.


To summarise, always use === when doing conditional statements unless you want to compare values of different data types.


* zero and an empty string are considered to be false and all other numbers and strings are considered to be true.

Saturday, 1 November 2008

SQL Server compatability level

When you upgrade to SQL Server 2005, you may find that some SQL statements are no longer valid and produce errors. A typical example is when you have 2 tables under different databases with the same name (the schema is irrelevant).

Assume that you have 2 databases, MyDatabase1 and MyDatabase2, each containing a table called MyTable. Both tables have a primary key called ID which are also foreign keys between Database1..MyTable and Database2..MyTable. The following SQL statement is valid under SQL Server 2000 but invalid under SQL Server 2005:

use [MyDatabase1]

select * from [MyTable]
inner join [Database2]..[MyTable] on [MyTable].[ID] = [Database2]..[MyTable].[ID]

SQL Server 2005 is more strict and won't allow you to reference MyTable of MyDatabase1 in this way, even though you've specified the default database (use [MyDatabase1]). Instead you'd have to change the statement:

select * from [Database1]..[MyTable]
inner join [Database2]..[MyTable] on [Database1]..[MyTable].[ID] = [Database2]..[MyTable].[ID]

Alternatively, you can change the compatability level on the nececssary database(s). This is a quick fix and should only be done if you can't easily modify the SQL code.

  1. Open Microsoft SQL Server Management Studio
  2. Expand the 'Databases' node
  3. Right click the database and choose 'Properties'
  4. Go to 'Options' and change the 'Compatability level' accordingly

The 3 compatability levels are:
  • SQL Server 7.0 (70)
  • SQL Server 2000 (80)
  • SQL Server 2005 (90)