7

CASEある文字列の長さを利用して別の文字列の結果を生成できる結果を取得できる SQL Select ステートメントで使用しようとしています。これらは、共通の ID を共有する 2 つのデータ セットの一致しないレコードを対象としていますが、バリアント データ ソースです。

ケースステートメントは以下のとおりです。

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

実行すると、次のエラーが表示されます。

メッセージ 102、レベル 15、状態 1、行 5 「=」付近の構文が正しくありません。

4

2 に答える 2

10

それぞれの値が必要であり、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()文字列を返しません。

EDIT: いくつかのコメントに対処する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
于 2012-05-02T02:52:34.573 に答える
2
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. 条件の場合は「Column1=」を削除します
  4. と置換する ''

この助けを願っています。

于 2012-05-01T23:54:09.123 に答える