使用Case来匹配sql server中的字符串?

时间:2012-05-01 23:30:08

标签: string tsql

我试图在SQL Select语句中使用CASE,这将允许我获得结果,我可以利用一个字符串的长度来生成另一个字符串的resutls。这些是针对共享公共ID的两个数据集的非匹配记录,但是是变体数据源。

案例陈述如下:

Select Column1, Column2, 
Case
When Column1 = 'Something" and Len(Column2) = '35' Then Column1 = "Something Else" and substring(Column2, 1, 35)
End as Column3
From  dbo.xxx

当我运行它时,我收到以下错误:

  

Msg 102,Level 15,State 1,Line 5'='附近的语法不正确。

2 个答案:

答案 0 :(得分:3)

您需要为每个WHEN设置一个值,并且应该有一个ELSE

Select Data_Source, CustomerID,
  CASE
    WHEN Data_Source = 'Test1' and Len(CustomerName) = 35 THEN 'First Value'
    WHEN Data_Source = 'Test2' THEN substring(CustomerName, 1, 35)
    ELSE 'Sorry, no match.'
    END AS CustomerName
  From dbo.xx

仅供参考:Len()不会返回字符串。

修改 解决一些注释的SQL Server答案可能是:

declare @DataSource as Table ( Id Int Identity, CustomerName VarChar(64) )
declare @VariantDataSource as Table ( Id Int Identity, CostumerName VarChar(64) )
insert into @DataSource ( CustomerName ) values ( 'Alice B.' ), ( 'Bob C.' ), ( 'Charles D.' )
insert into @VariantDataSource ( CostumerName ) values ( 'Blush' ), ( 'Dye' ), ( 'Pancake Base' )

select *,
  -- Output the CostumerName padded or trimmed to the same length as CustomerName.  NULLs are not handled gracefully.
  Substring( CostumerName + Replicate( '.', Len( CustomerName ) ), 1, Len( CustomerName ) ) as Clustermere,
  -- Output the CostumerName padded or trimmed to the same length as CustomerName.  NULLs in CustomerName are explicitly handled.
  case
    when CustomerName is NULL then ''
    when Len( CustomerName ) > Len( CostumerName ) then Substring( CostumerName, 1, Len( CustomerName ) )
    else Substring( CostumerName + Replicate( '.', Len( CustomerName ) ), 1, Len( CustomerName ) )
    end as 'Crustymore'
  from @DataSource as DS inner join
    @VariantDataSource as VDS on VDS.Id = DS.Id

答案 1 :(得分:1)

Select 
    Column1, 
    Column2, 
    Case 
      When Column1 = 'Something' and Len(Column2) = 35 
      Then 'Something Else' + substring(Column2, 1, 35) 
    End as Column3 
From dbo.xxx

上更新您的查询
  1. 使用'+'表示字符串concat
  2. len()返回int,不需要使用''
  3. 在条件
  4. 的情况下删除“Column1 =”
  5. 将“”替换为''
  6. 希望这有帮助。