SQL 如何在sql server 2008的存储过程中使用if比较两个字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2877560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 06:18:22  来源:igfitidea点击:

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

sqlsql-servertsqlsql-server-2008string-comparison

提问by Vishal

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

回答by OMG Ponies

Two things:

两件事情:

  1. Only need one (1) equals sign to evaluate
  2. You needto specify a length on the VARCHAR - the default is a single character.
  1. 只需要一 (1) 个等号来评估
  2. 需要在 VARCHAR 上指定长度 - 默认为单个字符。


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 -

VARCHAR(10)表示 VARCHAR 最多可容纳 10 个字符。更多行为示例 -

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

...将返回“不”。

回答by Andrey

declare @temp as varchar
  set @temp='Measure'
  if(@temp = 'Measure')
Select Measure from Measuretable
else
Select OtherMeasure from Measuretable

回答by John Sinclair

What you want is a SQL case statement. The form of these is either:

你想要的是一个 SQL case 语句。这些的形式是:

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

or:

或者:

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

In your example you are after:

在你的例子中,你在追求:

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

select case @temp 
   when 'Measure' then Measure 
   else OtherMeasure end
from Measuretable

回答by Chetan Hirapara

You can also try this for match string.

你也可以试试这个匹配字符串。

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'