使用大小写匹配 SQL 服务器中的字符串



我正在尝试在 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,级别 15,状态 1,第 5 行 "="附近的语法不正确。

你需要

为每个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
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. 使用"+"表示字符串连接
  2. len() 返回 int,无需使用 ''
  3. 在条件的情况下删除"列 1 ="
  4. 将"改为"

希望这有帮助。