在 where 语句中区分大小写和 COLLATE SQL_Latin1_General_CP1_CI_AS

Case and COLLATE SQL_Latin1_General_CP1_CI_AS in where statement

我正在处理一个有两个输入参数的存储过程,我需要使用 COLLATE SQL_Latin1_General_CP1_CI_AS 以便我可以查询不区分大小写的结果;但是,我还想允许带有输入的显示所有选项。我还没有找到 Collat​​e 在案例陈述中工作的方法。注意:作为解决方法,我将针对选择值 and/or 的不同场景使用 4 个不同的 If 语句进行编码显示全部,但如果可能的话,我希望更简洁。当前代码如下

Declare 
@INCo as bCompany,
@MatBeg as bMatl,
@MatEnd as bMatl,
@Catg as bGroup,
@Model as VarChar(20),
@PatternM as VarChar(20),
@SellOn as VarChar(20),
@PatternS as VarChar(20),
@ShowZero as bYN

set @INCo = '1'
set @MatBeg = '0'
set @MatEnd = 'ZZZZZZZZZZ'
set @Catg = '0'
set @Model = '637'
set @SellOn = 'EBAY'
set @ShowZero = 'Y' 


begin
set @PatternM = '%' + @Model + '%';
set @PatternS = '%' + @SellOn + '%';

select i.INCo, i.Material, h.Description, h.Category, c.Description as CatgDesc, i.Booked as Quantity, i.PhyLoc, p.Storage, 
    i.udModelFit as FitsModel, i.udSellPriceNew as LikeNewSellPrice, i.udSellPriceUsed as UsedSellPrice, i.udSellingOn as SellingOn

from INMT i
    left outer join HQMT h on i.MatlGroup=h.MatlGroup and i.Material=h.Material
    left outer join HQMC c on h.MatlGroup=c.MatlGroup and h.Category=c.Category
    left outer join udPhysicalloc p on i.PhyLoc=p.Physicalloc

where i.INCo = (CASE when @INCo <> 0 then @INCo else i.INCo END)
    and i.Material >= @MatBeg and i.Material <= @MatEnd
    and c.Category = (CASE when @Catg <> 0 then @Catg else c.Category END)
    and i.udModelFit COLLATE SQL_Latin1_General_CP1_CI_AS like @PatternM
    and i.udSellingOn COLLATE SQL_Latin1_General_CP1_CI_AS like @PatternS
    and i.Booked >= (CASE when @ShowZero = 'N' then 1 else 0 END)
END

如果我只关心@Model 和@SellOn 的不区分大小写的结果,那么这段代码工作得很好。但是,就像我拥有的​​其他参数一样,我想包含一些允许显示该参数的所有结果的内容。类似于:

i.udModelFit = (CASE when @Model <> 'ALL' then COLLATE SQL_Latin1_General_CP1_CI_AS like @PatternM else i.udModelFit END)

因此,作为示例,我想输入@Model = 'ALL' 和@SellOn = 'eBay',结果将是 Sell On = EBAY(不区分大小写)


更新:我能够将 Where 修改为以下内容,现在我得到了想要的结果。

where i.INCo = (CASE when @INCo <> 0 then @INCo else i.INCo END)
    and i.Material >= @MatBeg and i.Material <= @MatEnd
    and c.Category = (CASE when @Catg <> 0 then @Catg else c.Category END)
    and (
        (@Model IS NULL or i.udModelFit COLLATE SQL_Latin1_General_CP1_CI_AS like @PatternM) 
        or ((i.udModelFit like '%' or i.udModelFit IS NULL) and @Model = 'ALL')
        )
    and (
        (@SellOn IS NULL or i.udSellingOn COLLATE SQL_Latin1_General_CP1_CI_AS like @PatternS)
        or ((i.udSellingOn like '%' or i.udSellingOn IS NULL) and @SellOn = 'ALL')
        )
    and i.Booked >= (CASE when @ShowZero = 'N' then 1 else 0 END)

您可以使用 and( (...) or (...) ) 例如

and (@Model = 'ALL' or i.udModelFit like @PatternM SQL_Latin1_General_CP1_CI_AS)

如果您想根据输入切换不同的搜索选项,您可能需要考虑使用动态 sql、and/or 添加 option (recompile) 来编写您的过程。

包罗万象的查询参考: