动态设置ORDER BY而不进行字符串连接

时间:2018-05-01 06:18:22

标签: sql-server node.js tsql

我在Express应用中使用mssql来查询数据库。

我的代码是:

router.get('/expedientes', function (req, res, next) {
  request.input('pageSize', sql.Int, parseInt(req.query.page_size));
  request.query('SELECT TOP (@pageSize) * FROM expedientes', function (err, result) {
    if (err) console.log(err)
    res.send(result.recordset);
  });
});

我想添加一个'命令dy'特色到路线。 我试过(没有运气)这个:

router.get('/expedientes', function (req, res, next) {
  request.input('pageSize', sql.Int, parseInt(req.query.page_size));
  request.input('orderBy', sql.Text, req.query.order_by);
  request.input('orderDir', sql.Text, req.query.order_dir);
  request.query('SELECT TOP (@pageSize) * FROM expedientes ORDER BY (@orderBy) (@orderDir)', function (err, result) {
    if (err) console.log(err)
    res.send(result.recordset);
  });
});

如何使用字符串连接执行此操作?文档对此功能并不清楚。

1 个答案:

答案 0 :(得分:2)

您可以使用CASE

SELECT TOP (@pageSize) * 
FROM expedientes 
ORDER BY CASE 
               WHEN @OrderBy = 'col1' AND @orderDir = 'ASC' THEN col1     
               --all columns in THEN part should have the same datatype
               WHEN @OrderBy = 'col2' AND @orderDir = 'ASC' THEN col2
               --  ...
         END,

         CASE 
               WHEN @OrderBy = 'col1' AND @orderDir = 'DESC' THEN col1     
               --should have the same datatype
               WHEN @OrderBy = 'col2' AND @orderDir = 'DESC' THEN col2
               --  ...
         END DESC
--OPTION(RECOMPILE);  -- to avoid expressions in final execution plan

<强> DBFiddle Demo