RAND SQL function
1. Usage of RAND to list 5 random products.
SQL Server Query 1
SELECT TOP 5 ProductID, ProductName, UnitPrice
FROM Products ORDER BY RAND();
Create SQL query with SqlQueryBuilder 1
var (sql1, parameters1) = new SqlQueryBuilder()
.Select().Top(5)
.Columns("ProductID", "ProductName", "UnitPrice")
.From("Products")
.OrderBy(new OrderBy().Set(new RAND()))
.Build();
Query build by SqlQueryBuilder 1
SELECT TOP 5 ProductID,
ProductName,
UnitPrice
FROM Products
ORDER BY RAND() ASC;
Parameters (If used)
Query Results 1:
|
ProductID |
ProductName |
UnitPrice |
1 |
1
|
Chai
|
18.0000
|
2 |
2
|
Chang
|
19.0000
|
3 |
3
|
Aniseed Syrup
|
10.0000
|
4 |
4
|
Chef Anton's Cajun Seasoning
|
22.0000
|
5 |
5
|
Chef Anton's Gumbo Mix
|
21.3500
|
2. Usage of RAND to display random numbers.
SQL Server Query 2
SELECT TOP 10 RAND() AS RandomNumber,
CustomerID, CompanyName, ContactName
FROM Customers
Create SQL query with SqlQueryBuilder 2
var (sql2, parameters2) = new SqlQueryBuilder()
.Select().Top(10)
.Column(new RAND(), "RandomNumber")
.Columns("CustomerID", "CompanyName", "ContactName")
.From("Customers")
.Build();
Query build by SqlQueryBuilder 2
SELECT TOP 10 RAND() AS RandomNumber,
CustomerID,
CompanyName,
ContactName
FROM Customers;
Parameters (If used)
Query Results 2:
|
RandomNumber |
CustomerID |
CompanyName |
ContactName |
1 |
0.845632530049035
|
ALFKI
|
Alfreds Futterkiste
|
Maria Anders
|
2 |
0.845632530049035
|
ANATR
|
Ana Trujillo Emparedados y helados
|
Ana Trujillo
|
3 |
0.845632530049035
|
ANTON
|
Antonio Moreno Taquería
|
Antonio Moreno
|
4 |
0.845632530049035
|
AROUT
|
Around the Horn
|
Thomas Hardy
|
5 |
0.845632530049035
|
BERGS
|
Berglunds snabbköp
|
Christina Berglund
|
6 |
0.845632530049035
|
BLAUS
|
Blauer See Delikatessen
|
Hanna Moos
|
7 |
0.845632530049035
|
BLONP
|
Blondesddsl père et fils
|
Frédérique Citeaux
|
8 |
0.845632530049035
|
BOLID
|
Bólido Comidas preparadas
|
Martín Sommer
|
9 |
0.845632530049035
|
BONAP
|
Bon app'
|
Laurence Lebihan
|
10 |
0.845632530049035
|
BOTTM
|
Bottom-Dollar Markets
|
Elizabeth Lincoln
|