PowerShell and SQL Server – Generating Data

In order to test the performance of a database, or application that uses it, where there are large volumes of data, it may be useful to generate data rather than having to enter it manually.

The following example demonstrates how to generate data for a table called ‘person’, which was used in the examples for importing and exporting data.

First of all, database connection variables are defined and the number of records to generate is specified. This can be set to any value, as long as there is enough space in the database to accommodate the records. A number of arrays are defined so that a random first name, last name and title can be selected for each record. The first name array also holds the gender associated with the name so that an appropriate title can be selected. A date range is also specified to allow for the generation of a random date of birth, along with other variables.

A ‘for’ loop is used to generate the desired number of records. A random number is generated to select a first name from the corresponding array and this is extracted, along with the gender. The same process occurs to extract a random last name. The gender is then used to extract a title from the appropriate array. The final random value generated is the date of birth.

Once all the values have been generated, an SQL ‘insert‘ statement is constructed and then executed. Feedback is provided as to the number of records added to the database. A ‘try-catch’ block is also used to catch any errors that may occur.

# Clear the console window.
Clear-Host

# Database connection variables.
$server = "localhost\MSSQLSERVERDEMO"
$database = "Demo"
$username = "DemoUN"
$password = "DemoPW"

# Number of records to generate.
[int] $recordsToGenerate = 500

# First names.
$fname = @(
    ("Oliver", "M"), ("Noah", "M"), ("Harry", "M"),
    ("Leo", "M"), ("Charlie", "M"), ("Jack", "M"),
    ("Freddie", "M"), ("Alfie", "M"), ("Archie", "M"),
    ("Theo", "M"), ("Olivia", "F"), ("Sophia", "F"),
    ("Amelia", "F"), ("Emily", "F"), ("Ava", "F"),
    ("Isla", "F"), ("Isabelle", "F"), ("Charlotte", "F"),
    ("Layla", "F"), ("Freya", "F")
)

# Last names.
$lname = @(
    "Smith", "Johnson", "Williams", "Jones",
    "Brown", "Davis", "Miller", "Wilson",
    "Taylor", "Anderson", "Thomas", "White",
    "Martin", "Thompson", "Robinson", "Clark",
    "Walker", "Young", "Wright", "Hill"
)

# Male titles.
$mtitle = @(
    "Mr", "Dr", "Prof"
)

# Female titles.
$ftitle = @(
    "Miss", "Mrs", "Ms", "Dr", "Prof"
)

# Dates for random date of birth range.
[datetime] $dateToday = Get-Date -UFormat "%Y-%m-%d"
[datetime] $startDob = (Get-Date).AddYears(-100).Date
[datetime] $endDob = (Get-Date).AddYears(-20).Date

# Random class and number.
$random = new-object random
[int] $randomNumber = 0

# New record values.
[string] $firstname = $null
[string] $lastname = $null
[string] $gender = $null
[string] $title = $null
[datetime] $dob = $startDob

# SQL variable.
[string] $sqlPersonInfo = $null

# Record count.
[int] $recordCount = 0

try
{

    # Generate specified number of records.
    for ($i = 1; $i -le $recordsToGenerate; $i++)
    {

        # Randomly select a first name and associated gender.
        $randomNumber = Get-Random -Minimum 0 -Maximum ($fname.Length - 1)
        $firstname =  $fname[$randomNumber][0]
        $gender = $fname[$randomNumber][1]

        # Randomly select a last name.
        $randomNumber = Get-Random -Minimum 0 -Maximum ($lname.Length - 1)
        $lastname =  $lname[$randomNumber]

        # Randomly select a title based on the gender.
        if ($gender.Equals("M"))
        {

            $randomNumber = Get-Random -Minimum 0 -Maximum ($mtitle.Length - 1)
            $title = $mtitle[$randomNumber]

        }
        else
        {

            $randomNumber = Get-Random -Minimum 0 -Maximum ($ftitle.Length - 1)
            $title = $ftitle[$randomNumber]

        }

        # Randomly select a date of birth.
        $dob = [Convert]::ToInt64( ($endDob.ticks * 1.0 - $startDob.Ticks * 1.0 ) `
        * $random.NextDouble() + $startDob.Ticks * 1.0 )
        $dob = $dob.Date

        # Query text.
        $sqlPersonInfo = `
            "INSERT INTO person " +
            "       (firstname, lastname, title, dob) " +
            "VALUES ('$firstname', '$lastname', '$title', '$dob')"

        # Execute the query.
        Invoke-Sqlcmd -ServerInstance $server -Database $database `
        -Username $username -Password $password -Query $sqlPersonInfo -ErrorAction Stop
            
        # Add one to the record count.
        $recordCount += 1

    }

    # Provide feedback on the number of records added.
    if ($recordCount -eq 0)
    {

        Write-Host "No new person records added."

    }
    elseif ($recordCount -eq 1)
    {

        Write-Host "$recordCount person record added."

    }
    else
    {

        Write-Host "$recordCount person records added."

    }


}
catch
{

    # Confirm error adding person information.
    Write-Host "Error adding person information."

}