Bạn cần phải có một giá trị cho mỗi WHEN
, và nên có một 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
FYI: Len()
không trả lại một chuỗi.
EDIT: Một SQL Server câu trả lời mà giải quyết một số ý kiến có thể là:
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
Đó SQL không có ý nghĩa. Bạn có thể đưa ra một số dữ liệu ví dụ và hiển thị những gì bạn mong đợi xảy ra không? –
Đây là sql chính xác: Chọn DATA_SOURCE, CustomerID, TRƯỜNG HỢP KHI DATA_SOURCE = 'Test1' và Len (CustomerName) = '35' Sau đó DATA_SOURCE = 'Test2' và substring (CustomerName, 1, 35) End AS CustomerName Từ dbo.xx – user1368436
Data_Source CustomerID CustomerName Kiểm tra xxx xxx PLC, (LONDON BR Test1 xxx xxx PLC (LONDON BR2) – user1368436