Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 985
Vishal Avatar asked May 20 '10 20:05

Vishal


People also ask

How do I check if two strings are equal in SQL?

MySQL STRCMP() Function The STRCMP() function compares two strings.

Can you use == to compare two strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.


1 Answers

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".

like image 89
OMG Ponies Avatar answered Oct 26 '22 23:10

OMG Ponies