言词犀利哥 發表於 2023-10-26 00:00:00

多条件查询的程序

<p>
        而在对用户进行查询时,也可能会使用到多种条件的查询方式,如通过工号查询、通过姓名查询、通过性别查询、通过学历查询等。也有可能会通过多种条件的组合查询,如查学历是大专的女员工等。<br>
        对于这种查询情况,通常的作法是让用户输入查询条件,再进行SQL语句组合来进行查询。如让用户输入工号、姓名等,单击提交按钮之后,在后台获得这些信息,如以下代码所示:</p>
<p class="codetitle">
        <span><u>复制代码</u></span> 代码如下:</p>
<p class="codebody">
        <br>
        //设置查询语句<br>
        string strSql = "SELECT * FROM where UserState=1 ";<br>
        //如果用户名不为空则添加查询条件<br>
        if (UserName!="")<br>
        {<br>
            strSql += "and (UserName'= "+UserName+"') ";<br>
        }<br>
        //如果性别不为空则添加查询条件<br>
        if (Sex!="")<br>
        {<br>
            strSql += "and (Sex'= "+Sex+"') ";<br>
        }</p>
<p>
        <br>
        在创建完SQL语句之后,执行该语句获得查询结果。<br>
        这种是使用得最多并且是最不安全的方法,因为这是最容易让别人SQL注入攻击的一个方式。<br>
        如果想要避免SQL注入攻击,可以将查询语句写在存储过程中,然后使用SqlParameter将参数传递给存储过程,但是,一个多条件查询的存储过程需要怎么写呢?<br>
        其实,这个存储过程并不难,可以使用以下方式:</p>
<p class="codetitle">
        <span><u>复制代码</u></span> 代码如下:</p>
<p class="codebody">
        <br>
        CREATE PROCEDURE .<br>
        @UserId varchar(50) = null,<br>
        @UserName varchar(20) = null,<br>
        @RealName varchar(20) = null,<br>
        @Sex bit = null,<br>
        @JobTitle varchar(50) = null,<br>
        @Organ varchar(50) = null,<br>
        @IDCardType smallint = null,<br>
        @IDCard varchar(50) = null,<br>
        @Mobile varchar(50) = null<br>
        AS<br>
        BEGIN<br>
        select * from <br>
        where UserId like case when @UserId is null then UserId else @UserId end<br>
        and UserName like case when @UserName is null then UserName else @UserName end<br>
        and RealName like case when @RealName is null then RealName else @RealName end<br>
        and Sex = case when @Sex is null then Sex else @Sex end<br>
        and JobTitle like case when @JobTitle is null then JobTitle else @JobTitle end<br>
        and Organ like case when @Organ is null then Organ else @Organ end<br>
        and IDCardType = case when @IDCardType is null then IDCardType else @IDCardType end<br>
        and IDCard like case when @IDCard is null then IDCard else @IDCard end<br>
        and Mobile like case when @Mobile is null then Mobile else @Mobile end<br>
        END</p>
頁: [1]
查看完整版本: 多条件查询的程序