Briana Briana - 11 months ago 48
SQL Question

IF-ELSE SQL Statement

I'm having a problem executing this SQL statement. I am new to TSQL and I have no idea how to fix this. Everytime I execute this, I get the error:

An expression of non-boolean type specified in a context where a
condition is expected, near ')'.

Incorrect syntax near the keyword 'else'.

SELECT Num from users where SUBSTRING(CAST(Num AS VARCHAR(6)),1,2) = 14
print 'Batch 2014';
print 'Batch 2013';

What I'm trying to do here is to search in my table all users with '13' as the first 2 numbers in the column 'Num', and then print 'Batch 2014' else 'Batch 2013' Please help :) thank you

Answer Source

It's best to avoid using if-else with exists. Why?

  1. You need to make sure at least one record exists in your table
  2. The other benefit of EXISTS is that once it finds a single record that matches it stops processing. This doesn't have a huge impact if you're checking on a primary key. It does have a big impact if you're checking for existance based on another field

if exists (SELECT Num from users where SUBSTRING(CAST(Num AS VARCHAR(6)),1,2) = 14) print 'Batch 2014'; ELSE print 'Batch 2013';