Как сравнить две строки, используя if в хранимой процедуре в SQL Server 2008? - PullRequest
11 голосов
/ 21 мая 2010

Я хочу сделать что-то вроде этого:

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

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

Ответы [ 4 ]

19 голосов
/ 21 мая 2010

Две вещи:

  1. Для оценки требуется только один (1) знак равенства
  2. Вам необходимо указать длину в VARCHAR - по умолчанию используется один символ.

Использование:

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

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

VARCHAR(10) означает, что VARCHAR будет содержать до 10 символов. Еще примеры поведения -

DECLARE @temp VARCHAR
    SET @temp = 'm'

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

... вернет "да"

DECLARE @temp VARCHAR
    SET @temp = 'mtest'

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

... вернет "нет".

1 голос
/ 03 мая 2016

Вы также можете попробовать это для строки соответствия.

DECLARE @temp1 VARCHAR(1000)
    SET @temp1 = '<li>Error in connecting server.</li>'
DECLARE @temp2 VARCHAR(1000)
    SET @temp2 = '<li>Error in connecting server. connection timeout.</li>'

IF @temp1 like '%Error in connecting server.%' OR @temp1 like '%Error in connecting server. connection timeout.%'
  SELECT 'yes'
ELSE
  SELECT 'no'
1 голос
/ 21 мая 2010

То, что вы хотите, это оператор SQL. Форма их:

  select case [expression or column]
  when [value] then [result]
  when [value2] then [result2]
  else [value3] end

или:

  select case 
  when [expression or column] = [value] then [result]
  when [expression or column] = [value2] then [result2]
  else [value3] end

В вашем примере вы после:

declare @temp as varchar(100)
set @temp='Measure'

select case @temp 
   when 'Measure' then Measure 
   else OtherMeasure end
from Measuretable
1 голос
/ 21 мая 2010
declare @temp as varchar
  set @temp='Measure'
  if(@temp = 'Measure')
Select Measure from Measuretable
else
Select OtherMeasure from Measuretable
...