将排序顺序作为参数传递

时间:2016-06-19 05:16:31

标签: javascript sql

参考下面的示例SQL语句。我能够将参数值传递给占位符'?'在声明中。但是,我想知道是否可以以相同的方式传递排序顺序?

所以不要这样:

//Create SQL query
var getAccountsTransactionsStatement = WL.Server.createSQLStatement(
  "SELECT transactionId, fromAccount, toAccount, transactionDate, transactionAmount, transactionType " +
  "FROM accounttransactions " +
  "WHERE accounttransactions.fromAccount = ? OR accounttransactions.toAccount = ? " +
  "ORDER BY transactionDate DESC " +
  "LIMIT 20;"
);

我可以拥有这个:

//Create SQL query
var getAccountsTransactionsStatement = WL.Server.createSQLStatement(
  "SELECT transactionId, fromAccount, toAccount, transactionDate, transactionAmount, transactionType " +
  "FROM accounttransactions " +
  "WHERE accounttransactions.fromAccount = ? OR accounttransactions.toAccount = ? " +
  "ORDER BY ? DESC " +
  "LIMIT 20;"
);

并调用它:

//Invoke prepared SQL query and return invocation result
function getAccountTransactions1(accountId){
  return WL.Server.invokeSQLStatement({
    preparedStatement : getAccountsTransactionsStatement,
    parameters : [accountId, accountId, transactionDate]
  });
}

1 个答案:

答案 0 :(得分:1)

两件事:

  1. 此查询文章:

    WHERE accounttransactions.fromAccount = ? OR accounttransactions.toAccount = ?
    

    可以替换为:

    WHERE ? in (accounttransactions.fromAccount, accounttransactions.toAccount)
    
  2. 不,你不能。参数是值 - 一种静态的东西 - 而列名不是。你可以通过使用s.t.以某种方式以有限的方式解决这个问题。像这样:

    ORDER BY 
      CASE ?
        WHEN 'transactionDate' THEN transactionDate
        WHEN 'someotherdate' THEN someotherdate
        ELSE DATE '2010-01-01'
      END
    
  3. 但请注意,这是一个混乱的结构。此外,根据您使用的数据库类型,您可能希望将所有列转换为一种数据类型,即字符串。所以to_char(transactionDate,'yyyy-mm-dd hh24:mm:ss')可能是有序的,但你需要确保在你的情况下排序是正确的(因为数字往往会像'2'>'那样混乱13' )。