在SQL Query中使用操作逻辑?

时间:2016-12-09 09:10:11

标签: asp.net sql-server

我在Employees页面中有一个读取URL参数的查询字符串 如果参数 ALL ,则从DataBase获取公司员工页面应显示所有员工,但 CompID 相同的特定ID它将只获得该公司的员工这样做我使用两个查询但我确信我只能使用一个查询来获得相同的结果 我的查询字符串参数是:

String CompID = HttpUtility.UrlDecode(Request.QueryString["CompID"]);

显示所有员工的SQL查询是:

Query1 = "SELECT TbEmp.empID, TbEmp.fName, TbEmp.lName, TbEmp.email," +
               " TbEmp.phoneNbr, TbEmp.compID, TbEmp.gender, " +
                "TbEmp.address, TbComp.compName From TbEmp" +
                " INNER JOIN TbComp on TbComp.compID = TbEmp.compID ORDER BY TbComp.compID"

显示特定公司员工的SQL查询是:

Query2 = "SELECT TbEmp.empID, TbEmp.fName, TbEmp.lName, TbEmp.email," +
        " TbEmp.phoneNbr, TbEmp.compID, TbEmp.gender, " +
        "TbEmp.address, TbComp.compName From TbEmp" +
        " INNER JOIN TbComp on TbComp.compID = TbEmp.compID WHERE TbEmp.compID = @CompID ORDER BY TbComp.compID DESC"

有人可以帮助我在一个查询中合并这两个查询吗?

2 个答案:

答案 0 :(得分:0)

这是一个简单的案例。假设您的@CompID是数字,并且您可以发送零以指示“全部”搜索...

INNER JOIN TbComp on TbComp.compID = TbEmp.compID 
WHERE (@CompID = 0) or (@CompID <> 0 and TbEmp.compID = @CompID) 
ORDER BY TbComp.compID DESC"

答案 1 :(得分:0)

虽然我不建议使用查询在asp.net中编写逻辑(而是使用带参数的存储过程)。 你可以这样做:

解决方案1:

string Query1 = "SELECT TbEmp.empID, TbEmp.fName, TbEmp.lName, TbEmp.email," +
               " TbEmp.phoneNbr, TbEmp.compID, TbEmp.gender, " +
                "TbEmp.address, TbComp.compName From TbEmp" +
                " INNER JOIN TbComp on TbComp.compID = TbEmp.compID " ;

String CompID = HttpUtility.UrlDecode(Request.QueryString["CompID"]);
if( CompID<>"")
{
  Query1 += " WHERE TbEmp.compID = " + CompID //Beware : Chance of injection
}
Query1 +=" ORDER BY TbComp.compID";

解决方案2:假设如果@CompID不存在则会传递null。

Query2 = "SELECT TbEmp.empID, TbEmp.fName, TbEmp.lName, TbEmp.email," +
        " TbEmp.phoneNbr, TbEmp.compID, TbEmp.gender, " +
        "TbEmp.address, TbComp.compName From TbEmp" +
        " INNER JOIN TbComp on TbComp.compID = TbEmp.compID WHERE
     TbEmp.compID = Isnull(@CompID, TbEmp.compID)  ORDER BY TbComp.compID DESC"