我在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);
});
});
我想在路线上添加“ order 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);
});
});
我如何使用字符串连接来做到这一点?文档尚不清楚此功能。
最佳答案
您可以使用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