Search code examples
c#asp.netsql-serverdata-layers

C#, ASP.NET core | SqlException: Incorrect syntax near the keyword 'TOP'


I was experimenting in ASP.NET Core with getting data from my small database. I want to select 2 random rows from my table, but I can not get it to work.

My database table:

My databasetable

I figured the error I because my SqlCommand is not correct, but I don't know how to make it correct.

My DAL:

public IEnumerable<IKarakter> GetSortedKarakters()
{
    using (SqlConnection connection = GetConnection())
    {
        connection.Open();

        var command = new SqlCommand("SELECT * FROM Karakter ORDER BY RAND() LIMIT 2;", connection);

        var reader = command.ExecuteReader();
        var sortedKarakters = new List<IKarakter>();

        while (reader.Read())
        {
            var karakter = new KarakterDTO
                        {
                            KarakterId = (int)reader["KarakterId"],
                            KarakterSoort = reader["KarakterSoort"]?.ToString(),
                            KarakterNaam = reader["KarakterNaam"]?.ToString()
                        };
            sortedKarakters.Add(karakter);
        }

        return sortedKarakters;
    }
}

The queries that I have tried:

  • SELECT * FROM Karatker ORDER BY RAND() LIMIT 10;
  • SELECT * FROM Karakter ORDER BY RAND() TOP 2;
  • SELECT * FROM Karakter TOP 2;
  • SELECT * FROM Karakter Limit 2;
  • SELECT TOP 2 * FROM Karakter ODER BY RAND();
  • SELECT TOP 2 FROM Karakter ODER BY RAND();

All the above queries throw the same error except for the keyword.

Can anyone help?

Edit: when I tried this query:

SELECT TOP 2 * 
FROM dbo.Karakter; 

it displays the first 2 records of the database, this prooves that the error is not a problem from the other layers, the only problem is the query itself.


Solution

  • The correct query is:

    SELECT TOP 2 * 
    FROM Karakter 
    ORDER BY NEWID();
    

    Found it on this site: https://www.petefreitag.com/item/466.cfm