I'm having an issue where I'm trying to select a random record from the table (or row) and display it. My code is below and below that is the output I get when I try to print the variable holding the SQL query.
@using WebMatrix.Data
@{
var r = new Random();
var RandNum100 = r.Next(100);
var db = Database.Open("words");
var word1 = db.Query("SELECT TOP 1 * FROM words ORDER BY NEWID()");
var word2 = db.Query("SELECT TOP 1 * FROM words ORDER BY NEWID()");
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Random Passphrase Generator.</title>
</head>
<body>
<center><h1><b>Random Passphrase Generator.</b></h1></center>
<br>
<br>
<center> You're random passphrase is:</center>
<br>
<br>
<br>
<font size="30"><center><b>@word1 <br> @word2<br> @RandNum100</b></center></font>
</body>
</html>
Random Passphrase Generator.
You're random passphrase is:
System.Collections.ObjectModel.ReadOnlyCollection`1[System.Object]
System.Collections.ObjectModel.ReadOnlyCollection`1[System.Object]
23
Sup3rLativ3
Member
14 Points
6 Posts
Retrieve random record using NEWID()
Jun 11, 2012 04:45 AM|LINK
Hi Everyone,
I'm having an issue where I'm trying to select a random record from the table (or row) and display it. My code is below and below that is the output I get when I try to print the variable holding the SQL query.
@using WebMatrix.Data @{ var r = new Random(); var RandNum100 = r.Next(100); var db = Database.Open("words"); var word1 = db.Query("SELECT TOP 1 * FROM words ORDER BY NEWID()"); var word2 = db.Query("SELECT TOP 1 * FROM words ORDER BY NEWID()"); } <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Random Passphrase Generator.</title> </head> <body> <center><h1><b>Random Passphrase Generator.</b></h1></center> <br> <br> <center> You're random passphrase is:</center> <br> <br> <br> <font size="30"><center><b>@word1 <br> @word2<br> @RandNum100</b></center></font> </body> </html>ANY help would be GREATLY appreciated.
RAZOR sql newid
Mikesdotnett...
All-Star
154927 Points
19867 Posts
Moderator
MVP
Re: Retrieve random record using NEWID()
Jun 11, 2012 12:05 PM|LINK
Use Database.QueryValue():
var word1 = db.QueryValue("SELECT TOP 1 * FROM words ORDER BY NEWID()"); var word2 = db.QueryValue("SELECT TOP 1 * FROM words ORDER BY NEWID()");Beginning ASP.NET Web Pages with WebMatrix | My Site | Twitter
Sup3rLativ3
Member
14 Points
6 Posts
Re: Retrieve random record using NEWID()
Jun 11, 2012 02:36 PM|LINK
Thanks very much Mike, I really appreciate it.
None of the tutorials or examples I found showed to use this over the normal query.
Thanks again.