将查询的参数设为可选参数吗?

我正在使用msSqlConnecter繁琐。我有一个查询,该查询根据前端提供的参数进行过滤。我希望参数是可选的,并允许用户不提供它们或仅提供两者之一。有没有一种方法可以基于field2的存在来放置if语句?

我遇到以下错误:

  

RequestError:参数'field2'的验证失败。无效的号码。

代码:

var thequery1 = `SELECT country,sales,[Units Sold] as sold,thedate
                 FROM financial
                 WHERE 1 = 1
                   AND country = @field1
                   AND [Units Sold] > @field2`;

Promise.all([queryTablewithPararams(thequery1,req.body.field1,req.body.field2)])
        .then(
            data => res.json(data)
        );

function queryTablewithPararams(thequery1,field1,field2) {
    return new Promise(function(resolve,reject) {
        var con = new msSqlConnecter.msSqlConnecter(config);
        con.connect().then(function() {
            new con.Request(thequery1)
                .addParam("field1",TYPES.VarChar,field1)
                .addParam("field2",TYPES.Int,field2)
                .onComplate(function(count,datas) {
                    resolve(datas);
                }).onError(function(err) {
                    console.log(err);
                }).Run();
        }).catch(function(ex) {
            console.log(ex);
        });
    });
}
true430 回答:将查询的参数设为可选参数吗?

只需先验证field2,然后再以性能计发送

  

if (isNaN(field2) || field2 == null) { field2 = 0; }

   function queryTablewithPararams(thequery1,field1,field2) {
        if (isNaN(field2) || field2 == null) { field2 = 0; }
        return new Promise(function(resolve,reject) {
            var con = new msSqlConnecter.msSqlConnecter(config);
            con.connect().then(function() {
                new con.Request(thequery1)
                    .addParam("field1",TYPES.VarChar,field1)
                    .addParam("field2",TYPES.Int,field2)
                    .onComplate(function(count,datas) {
                        resolve(datas);
                    }).onError(function(err) {
                        console.log(err);
                    }).Run();
            }).catch(function(ex) {
                console.log(ex);
            });
        });
    }
,

采纳Joby的OP评论中的建议似乎可以解决它。

var thequery1 = `SELECT country,sales,[Units Sold] as sold,thedate
                     FROM financial
                     where 1 = 1
                     and country = @field1
                     and [Units Sold] > @field2`
if(req.body.field1){
    thequery1 = thequery1 + 'and country = @field1'
}
if(req.body.field2 > 0 ){
    thequery1 = thequery1 + 'and [Units Sold] > @field2'
}
本文链接:https://www.f2er.com/3162151.html

大家都在问