Case和COLLATE SQL_Latin1_General_CP1_CI_AS在where语句中

时间:2017-04-27 18:35:13

标签: sql-server-2008 stored-procedures case case-sensitive collate

我正在处理一个存储过程,它有两个输入参数,我需要使用COLLATE SQL_Latin1_General_CP1_CI_AS,以便我可以查询非大小写敏感的结果;但是,我还想允许输入显示所有选项。我没有找到让Collat​​e在案例陈述中工作的方法。注意:作为一种解决方法,我将使用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 =&#39; ALL&#39;和@SellOn =&#39; eBay&#39;并且结果将是具有Sell On = EBAY(非区分大小写)的任何模型

更新:我能够修改以下内容,现在我得到了预期的结果。

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)

1 个答案:

答案 0 :(得分:1)

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

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

如果要根据输入切换不同的搜索选项,您可能需要考虑使用动态sql编写程序,和/或添加option (recompile)

Catch-all查询参考: