Jump to content

Using LIMIT or TOP in MSSQL


SarahB12

Recommended Posts

Hey guys, I'm trying to limit my query to 5 results, but TOP is not working and LIMIT obviously does not work (I usually work with MySQL).

 

Here is my query:

$query = "SELECT PERSON.PERSON_ID, PERSON.LAST_NAME, PERSON.FIRST_NAME FROM PERSON where PERSON.LAST_NAME like '%$q%' or PERSON.FIRST_NAME like '%$q%' order by PERSON.LAST_NAME";

Can someone please point me in the right direction for limiting the query to 5 results?

 

Thank you!

~ Sarah

Link to comment
Share on other sites

$query = "SELECT TOP 5 PERSON.PERSON_ID, PERSON.LAST_NAME, PERSON.FIRST_NAME FROM PERSON where PERSON.LAST_NAME like '%$q%' or PERSON.FIRST_NAME like '%$q%' order by PERSON.LAST_NAME";
That should be all you need to do.
Link to comment
Share on other sites

$query = "SELECT TOP 5 PERSON.PERSON_ID, PERSON.LAST_NAME, PERSON.FIRST_NAME FROM PERSON where PERSON.LAST_NAME like '%$q%' or PERSON.FIRST_NAME like '%$q%' order by PERSON.LAST_NAME";
That should be all you need to do.

 

I have tried both "SELECT TOP 5" and "SELECT TOP (5)". Here is the error that is generated:

Fatal Error:  Uncaught exception 'com_exception' with message '<b>Source:</b> Microsoft OLE DB Provider for SQL Server<br/><b>Description:</b> Line 1: Incorrect syntax near '5'.' in C:\xampp\apps\wordpress\htdocs\autocomplete-search\search.php:9
Stack trace:
#0 C:\xampp\apps\wordpress\htdocs\autocomplete-search\search.php(9): com->execute('SELECT TOP 5 PE...')
#1 {main}
  thrown in
Link to comment
Share on other sites

What database software are you using, and what version? Also what functions are you using to connect to the database from PHP?

 

SELECT TOP 5 ... works fine for me. TOP has been supported for as long as I have been using SQL Server (since version 2000).

Link to comment
Share on other sites

SQL Server 2000.

 

Here is my connection string: 

$conn = new COM ("ADODB.Connection") or die("Cannot start ADO");

//define connection string, specify database driver
$connStr = "Provider=sqloledb;Data Source=SQLDB;Initial Catalog=PERSONDB;User Id=*****;Password=*****";

$conn->open($connStr); //Open the connection to the database

$query = "SELECT TOP (5) PERSON.PERSON_ID, PERSON.LAST_NAME, PERSON.FIRST_NAME FROM PERSON where PERSON.LAST_NAME like '%$q%' or PERSON.FIRST_NAME like '%$q%' order by PERSON.LAST_NAME";

$rs = $conn->execute($query);

Thank you.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.