A lot of business logic still lives in SQL Server: invoices that go overdue, orders that ship, backups that fail, a nightly check that finds trouble. Sooner or later someone asks for a text when it happens. You could reach for CLR or xp_cmdshell from T-SQL, but there's a calmer way. Let the database record what needs to be sent, and let a job step run a small script that does the sending.

We make Ready, so the script uses the Ready messaging API and only the request shape we document. The design is the useful part, and it holds for any provider: a queue table, one script, a stable idempotency key per row, and a nonzero exit code when something goes wrong so Agent can tell you.

Why not call the API from T-SQL

It's possible to make HTTP calls from inside the database engine, but it's rarely a good idea. A network call inside a transaction holds locks while it waits. A slow API turns into a slow query. Enabling OLE automation or xp_cmdshell widens your attack surface, and many security teams won't allow it at all.

Splitting the work keeps each part simple:

  1. T-SQL decides who should get a text and writes a row to a queue table.
  2. A job step sends. A script reads pending rows, calls the API, and marks each row.
  3. SQL Server Agent schedules the job and alerts an operator if a step fails.

The queue table doubles as your audit trail. Each row says what was supposed to go out, to whom, and what happened.

The queue table

CREATE TABLE dbo.PendingTexts (
    Id          INT IDENTITY PRIMARY KEY,
    Phone       VARCHAR(20)   NOT NULL,   /* E.164, like +12125550199 */
    Body        NVARCHAR(600) NOT NULL,
    Status      VARCHAR(10)   NOT NULL DEFAULT 'pending',
    Attempts    INT           NOT NULL DEFAULT 0,
    SentAt      DATETIME2     NULL,
    LastError   VARCHAR(200)  NULL
);

Your own business logic inserts into it, from a trigger, a stored procedure or an earlier job step. Store numbers in E.164 so the script never has to guess. Our guide to E.164 formatting explains the format. The row's Id becomes the idempotency key, which is what makes retries safe.

The script

This PowerShell script reads pending rows, sends each one and records the result. It assumes the SqlServer module (for Invoke-Sqlcmd) is installed on the machine that runs the job:

Import-Module SqlServer
$server = "localhost"
$db     = "Operations"

$rows = Invoke-Sqlcmd -ServerInstance $server -Database $db -Query @"
SELECT TOP 50 Id, Phone, Body FROM dbo.PendingTexts
WHERE Status = 'pending' AND Attempts < 5 ORDER BY Id
"@

$failures = 0
foreach ($r in $rows) {
    $headers = @{
        "X-API-Key"       = $env:READY_API_KEY
        "Idempotency-Key" = "pending-text-$($r.Id)"
    }
    $payload = @{ to = $r.Phone; body = $r.Body; consent_attested = $true } | ConvertTo-Json

    try {
        Invoke-RestMethod -Method Post -Uri "https://api.tryready.com/v1/messages" `
            -Headers $headers -ContentType "application/json" -Body $payload -TimeoutSec 20 | Out-Null
        Invoke-Sqlcmd -ServerInstance $server -Database $db -Variable "Id=$($r.Id)" `
            -Query "UPDATE dbo.PendingTexts SET Status='sent', SentAt=SYSUTCDATETIME() WHERE Id=`$(Id)"
    }
    catch {
        $failures++
        $code = $_.Exception.Response.StatusCode.value__
        $final = if ($code -and $code -ge 400 -and $code -lt 500 -and $code -ne 409 -and $code -ne 429) { "failed" } else { "pending" }
        Invoke-Sqlcmd -ServerInstance $server -Database $db -Variable "Id=$($r.Id)", "St=$final", "Code=$code" `
            -Query "UPDATE dbo.PendingTexts SET Status='`$(St)', Attempts=Attempts+1, LastError='HTTP `$(Code)' WHERE Id=`$(Id)"
    }
}

if ($failures -gt 0) { Write-Error "$failures text(s) failed"; exit 1 }

What's worth noticing:

  • The key is pending-text-<Id>. If the script sends a text and then dies before it can mark the row, the next run sends the same key. The API treats it as the same send, so nobody gets a duplicate. That's why the key comes from the row and not from a fresh GUID each run. Our post on deterministic idempotency keys explains the reasoning.
  • Permanent refusals stop retrying. A 4xx other than 409 or 429 means the request or recipient is wrong, so the row is marked failed for a person to look at. Everything else stays pending and gets another go, up to five attempts.
  • The script ends with exit code 1 when anything failed. That's what turns a quiet problem into a visible one.

The $(Id) placeholders are sqlcmd variables, which keeps values out of string concatenation. Test the script from a console against a copy of the table before you schedule it, because quoting rules differ between PowerShell versions. For a simpler standalone version of the call, see our PowerShell guide, or the Python guide if you'd rather not use PowerShell.

Wire it into SQL Server Agent

Create a job with one step. Two common setups:

Step typeCommandNotes
PowerShellThe script bodyRuns in the Agent PowerShell subsystem. Needs the module available to the Agent account.
Operating system (CmdExec)powershell.exe -NoProfile -File C:\jobs\send-texts.ps1Runs a script file. Easy to version in source control.

Then set the details that matter:

  • Run as. Use a proxy account with only the rights the script needs. Set READY_API_KEY as a machine-level environment variable that account can read. Don't put the key in the job step text, where anyone with msdb access can read it. Our key security post covers storage and rotation.
  • Schedule. Every minute or two suits alerts. Agent won't start a job that's still running, so a slow run can't overlap itself.
  • Notifications. Set the job to notify an operator on failure. A nonzero exit code from the script fails the step, and the operator hears about it.

Quiet hours, opt-outs and consent

Three rules shape what you queue:

  • Consent. consent_attested: true is your promise the recipient agreed. Texting your own staff for operational alerts is fine when they've agreed. Texting customers needs their consent, and Ready doesn't keep a per-contact opt-in record for you.
  • Opt-outs. A number that's opted out is refused up front and not charged. Don't retry it. Mark it failed and, if you can, sync the opt-out back to your own data.
  • Quiet hours. An API text during the recipient's quiet hours is held only if the window opens soon, otherwise it's refused with a 409. The script above leaves a 409 row as pending, which is the right call for a job that runs again in a minute. The quiet-hours guide covers sending with a hold instead.

For alerts to a handful of people, see our overview of business SMS notification and alert systems for what to alert on and how to avoid noise.

What it costs

Each segment on the Standard rate is $0.0075 plus a $0.0045 carrier fee. As an example, a job that sends 300 one-segment overdue notices a month costs 300 × ($0.0075 + $0.0045) = $3.60, plus the $2 monthly number. That all-in figure excludes screening, the optional Scrub lists and Number validation switches. An account can send up to 500 texts a calendar month before its registration is approved; most approvals take 2 to 7 days. See pricing.

Ready's all-in prices per segment include the carrier fee but not screening: Scrub lists and Number validation, the two switches in Settings under Compliance, each add $0.003 per segment when switched on, shown as screening on your bill, and both are off by default. Unless you turn the opt-out footer off, the first text to each contact, and one again from time to time, also gets "Reply STOP to opt out" and your business name if the message does not already have them, so a text close to the segment limit can bill one more segment.

Accounts opened before November 12, 2026 keep their signup prices, shown under Billing.

The short version

Let T-SQL write intent to a table, let a small script do the network call, key every send to the row, and let a nonzero exit code reach your Agent operator. You can build and test the whole thing on a test key, which simulates every send with no card, number or charge, and start texting today when it works.