I am attempting to retrieve a random row in my table from Visual Studio's database. However, it is unable to retrieve a random row and throws this specific exception:
System.Data.SqlClient.SqlException: 'Incorrect syntax near 'LIMIT'.'
This is my function code to retrieve a random table row:
Voucher randomVoucher = null;
int voucherID;
string voucherName, voucherDescription, discountCode;
decimal discountAmount;
string queryStr = "SELECT * FROM Voucher ORDER BY RAND() LIMIT 1; ";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
voucherID = int.Parse(dr["VoucherID"].ToString());
voucherName = dr["VoucherName"].ToString();
voucherDescription = dr["VoucherDescription"].ToString();
discountAmount = decimal.Parse(dr["DiscountAmount"].ToString());
discountCode = dr["DiscountCode"].ToString();
randomVoucher = new Voucher(voucherID, voucherName, voucherDescription, discountAmount, discountCode);
}
else
{
randomVoucher = null;
}
conn.Close();
dr.Close();
dr.Dispose();
return randomVoucher;