首页 > 解决方案 > 仅使用填充的文本框执行搜索

问题描述

我有一个带有不同搜索选项的搜索栏,我希望 SQL 查询仅使用填充的文本框进行搜索

当我使用 if 语句(不是最佳实践)有一个只有两个搜索选项(名称和代码)的搜索栏时,我制作了一个简单的 SP,它运行良好。但是,现在我有 4-5 个元素的搜索 bbar,IF 语句似乎不是性能的最佳实践

这是我为只有 2 个搜索选项的情况所做的程序:

@Code_client nvarchar(50),
@Intitule_client varchar(100)
as 
IF (@Code_client is not NULL AND @Code_client!='')
   BEGIN
   IF (@Intitule_client IS not NULL AND @Intitule_client!='')
      select * from Clients where Code_client=@Code_client and Intitule_client=@Intitule_client
   ELSE
      select * from Clients where Code_client=@Code_client
   END
ELSE IF (@Intitule_client is not null AND @Intitule_client!='')
    BEGIN
    select * from Clients where Intitule_client=@Intitule_client
    END

但对于这种情况,我有 4 个这样的搜索选项:

<div id="chercher_employe" class="Rechercher">
                <ul>
                    <li>
                        <asp:TextBox runat="server" ID="chercher_employe_Nom" CssClass="Input" placeholder="Nom employe"></asp:TextBox>
                    </li>

                    <li>
                        <asp:TextBox runat="server" ID="chercher_employe_Departement" CssClass="Input" placeholder="Departement"></asp:TextBox>
                    </li>

                    <li>
                        <asp:TextBox runat="server" ID="chercher_employe_occupation" CssClass="Input" placeholder="Occupation"></asp:TextBox>
                    </li>

                    <li>
                        <asp:TextBox runat="server" ID="chercher_employe_IntituleProfil" CssClass="Input" placeholder="Profil"></asp:TextBox>
                    </li>

                    <li>
                        <asp:LinkButton runat="server" CssClass="button">  <i class="fas fa-search"></i> </asp:LinkButton>
                    </li>
                </ul>
            </div>

除了将 if 语句与 C# 或 SQL 一起使用之外,我想不出另一种方法,请问有什么建议吗?

标签: c#sqlasp.netsql-server

解决方案


if 语句只不过是一个逻辑含义

a -> b如果 a 那么 b

也可以写成

!a or b不是 a 或 b

所以你的 if 语句

IF (@Intitule_client IS not NULL AND @Intitule_client!='')
      select * from Clients where Code_client=@Code_client and Intitule_client=@Intitule_client

可以翻译为(使用德摩根定律简化双重否定(not(a or b) <=> not(a) and not(b)

SELECT * 
FROM Clients
WHERE (@Intitule_client IS NULL OR @Intitule_client = '' OR Intitule_client = @Intitule_client) AND Code_client = @Code_client

然后,您可以使用此模式构建更复杂的查询。


推荐阅读