1

I would like to query MS SQL Server instance to serve a very simple POST request. I am using nodejs + express. The following code (async version) considers only first input types only and therefore returns error -

  let pool = await sql.connect(dbCredentials);
  let bookName = "string to be matched" ; 
  let ranksVal= 10
  
  let result = await pool
    .request()
    .input("item", sql.VarChar, bookName)
    .input("ranksVal", sql.Int , ranksVal)
    .query(`select top @ranksVal * from dbTable where book = @item order by counts desc`);

Ideally, the above code should return a result for the following SQL query :

 select top 10 * from dbTable where book = "string to be matched" order by counts desc

Alternatively, the following solution works :

  let result = await pool
    .request()
    .input("item", sql.VarChar, bookName)
    .query(`select top ${ranksVal} * from dbTable where book = @item order by counts desc`);

But I would like to understand how can we pass multiple values to req.input() method. Thank you.

1 Answer 1

2

To use an expression or a parameter in a TOP values clause you must use parentheses. eg

 .query(`select top (@ranksVal) * from dbTable where book = @item order by counts desc`);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.