代码之家  ›  专栏  ›  技术社区  ›  Vishal

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

  •  11
  • Vishal  · 技术社区  · 15 年前

    我想这样做:

    declare @temp as varchar
        set @temp='Measure'
    
    if(@temp == 'Measure')
       Select Measure from Measuretable
    else
       Select OtherMeasure from Measuretable
    
    4 回复  |  直到 9 年前
        1
  •  19
  •   OMG Ponies    15 年前

    两件事:

    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'
    

    …将返回“否”。

        2
  •  1
  •   Andrey    15 年前
    declare @temp as varchar
      set @temp='Measure'
      if(@temp = 'Measure')
    Select Measure from Measuretable
    else
    Select OtherMeasure from Measuretable
    
        3
  •  1
  •   John Sinclair    15 年前

    您需要的是一个SQL case语句。 其形式为:

      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
    
        4
  •  1
  •   Chetan Hirapara    9 年前

    您也可以尝试将其用于匹配字符串。

    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'