How to Compare two strings using a if in a stored procedure in sql server 2008?

Vishal picture Vishal · May 20, 2010 · Viewed 115.2k times · Source

I want to do something like this:

declare @temp as varchar
    set @temp='Measure'

if(@temp == 'Measure')
   Select Measure from Measuretable
else
   Select OtherMeasure from Measuretable

Answer

OMG Ponies picture OMG Ponies · May 20, 2010

Two things:

  1. Only need one (1) equals sign to evaluate
  2. You need to specify a length on the VARCHAR - the default is a single character.

Use:

DECLARE @temp VARCHAR(10)
    SET @temp = 'm'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

VARCHAR(10) means the VARCHAR will accommodate up to 10 characters. More examples of the behavior -

DECLARE @temp VARCHAR
    SET @temp = 'm'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

...will return "yes"

DECLARE @temp VARCHAR
    SET @temp = 'mtest'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

...will return "no".