1

I was wondering how can i get n number of samples randomly from a local database using c#

What I have done so far.

"SELECT TOP "+n+" QUESTION,C1,C2,C3,C4,ANSWER FROM qPIPE WHERE CONTENT = 'Topic' ORDER BY RAND()"

"SELECT QUESTION,C1,C2,C3,C4,ANSWER FROM qPIPE WHERE CONTENT = 'Topic' ORDER BY RAND() LIMIT "+n+""

error: Additional information: Undefined function 'RAND' in expression.

"SELECT TOP "+n+" QUESTION,C1,C2,C3,C4,ANSWER FROM qPIPE WHERE CONTENT = 'Topic' ORDER BY NEWID()"

Additional information: Undefined function 'NEWID' in expression.

My connection string

ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0DataSource=|DataDirectory|\questionbank.accdb";

But when I try to query it to MS SQL

SELECT TOP n QUESTION, C1, C2, C3, C4, ANSWER FROM qPIPE WHERE CONTENT = 'Topic' ORDER BY NEWID()

It works fine. Get n number of questions from the table with the matching topic.

Im using MVS 2015, MSSMS 2017. Working on a win form.

edit:

using ORDER BY RND()

edit:

connection.Open();
            OleDbCommand command = new OleDbCommand();
            command.Connection = connection;
            command.CommandText = "SELECT TOP 2 QUESTION,C1,C2,C3,C4,ANSWER FROM qPIPE WHERE CONTENT = 'Thermodynamics' ORDER BY RND()";
            OleDbDataAdapter dAdap = new OleDbDataAdapter(command);
            DataTable dTable = new DataTable();
            dAdap.Fill(dTable);
            dataGridView1.DataSource = dTable;
connection.Close();
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275

2 Answers2

3

In SQL Server, you can use the NEWID() function:

SELECT TOP "+n+" QUESTION,C1,C2,C3,C4,ANSWER
FROM qPIPE
WHERE CONTENT = 'Topic'
ORDER BY NEWID();

In MS Access, you can use RND():

SELECT TOP "+n+" QUESTION,C1,C2,C3,C4,ANSWER
FROM qPIPE
WHERE CONTENT = 'Topic'
ORDER BY RND();
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

You should avoid concatenating SQL string (possible SQL injection). You could pass n as parameter:

DECLARE @n INT = 5;

SELECT TOP (n) QUESTION, C1, C2, C3, C4, ANSWER
FROM qPIPE
WHERE CONTENT = 'Topic'
ORDER BY NEWID();

EDIT:

Based on your connection string I assume that you are connecting to MS Access Database. Then you may use ORDER BY RND(-(100000*ID)*Time()). Based on kobik's comment

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275