Call a stored procedure¶
Run a stored procedure with EXEC, through execute_query or, with
parameters, execute_rpc. The examples use two procedures:
run("CREATE PROCEDURE dbo.add_reading @device VARCHAR(32), @temperature REAL AS "
"BEGIN SET NOCOUNT ON; "
"IF @temperature > 80 RAISERROR('temperature out of range', 16, 1); "
"ELSE INSERT INTO dbo.readings (device, temperature) VALUES (@device, @temperature); END");
run("CREATE PROCEDURE dbo.count_readings @device VARCHAR(32), @total INT OUTPUT AS "
"BEGIN SELECT COUNT(*), @device FROM dbo.readings WHERE device = @device; "
"SELECT @total = COUNT(*) FROM dbo.readings; RETURN 7; END");
add_reading inserts a reading, or raises an error if the temperature is out
of range. count_readings returns a result set, an OUTPUT parameter and a
return value.
Call it with fixed arguments¶
When the arguments are part of your code, put the whole EXEC in a query:
// Fixed arguments: EXEC in a plain query
const auto qr = driver.execute_query("EXEC dbo.add_reading 'greenhouse-1', 21.5");
std::printf("exec: %s\n", qr ? "ok" : "failed");
Pass values from your program¶
For values that come from your program (sensor readings, user input), use
parameters: @p0, @p1, ... in the order of the bindings, passed on to the
procedure's parameters by name. Don't paste the values into the SQL text;
see Run parameterized queries for why.
// Values from the program: parameters, passed on to the procedure
tdsl::sql_parameter_varchar device{"greenhouse-1"};
tdsl::sql_parameter_float4 temperature{22.0f};
tdsl::sql_parameter_binding args []{device, temperature};
const auto rr = driver.execute_rpc(
tdsl::string_view{"EXEC dbo.add_reading @device = @p0, @temperature = @p1"}, args);
std::printf("exec with parameters: %s\n", rr ? "ok" : "failed");
Read what it returns¶
Every SELECT in the procedure returns a result set, and each row arrives
at the row callback. When a procedure returns several result sets, the
callback receives them in order; use the column metadata to tell them apart:
// One callback receives the rows of every result set the procedure
// returns. The column metadata tells them apart, e.g. by column count.
static void print_row(void *, const tdsl::tds_colmetadata_token & columns,
const tdsl::tdsl_row & row) {
if (columns.columns.size() == 2) {
const auto device = row [1].as<tdsl::char_view>();
std::printf("count: %d (%.*s)\n", static_cast<int>(row [0].as<tdsl::int32_t>()),
static_cast<int>(device.size()), device.data());
} else {
std::printf("value: %d\n", static_cast<int>(row [0].as<tdsl::int32_t>()));
}
}
tdslite has no bindings for OUTPUT parameters or the return value. Catch
them in variables in the same request, then SELECT them:
// Result sets, the OUTPUT parameter and the return value. tdslite
// has no OUTPUT bindings: catch them in variables, then SELECT them.
tdsl::sql_parameter_binding count_args []{device};
const auto cr = driver.execute_rpc(
tdsl::string_view{"DECLARE @total INT, @status INT; "
"EXEC @status = dbo.count_readings "
" @device = @p0, @total = @total OUTPUT; "
"SELECT @total; SELECT @status;"},
count_args, tdsl::rpc_mode::executesql, print_row);
std::printf("count: %s\n", cr ? "ok" : "failed");
This prints:
The first line comes from the procedure's own SELECT, then the OUTPUT
parameter (@total), then the return value (@status).
Detect errors inside the procedure¶
An error raised inside a procedure goes to the info callback, as usual. The
result of the call does not always report it: when the procedure uses
SET NOCOUNT ON (most do) and the error doesn't end it, e.g. a RAISERROR
or a failed INSERT, the call reports success. THROW, and errors that end
the procedure, do make the call fail with server_error.
To catch every error, count them in the info callback:
// Errors the server reported for the current request
static int server_errors = 0;
static void print_message(void *, const tdsl::tds_info_token & token) noexcept {
if (not token.is_error()) {
return;
}
server_errors++;
std::printf("server error %u: ", static_cast<unsigned>(token.number));
for (const char16_t c : token.msgtext) {
std::putchar(static_cast<char>(c));
}
std::putchar('\n');
}
and check the count along with the result:
// RAISERROR in a procedure with SET NOCOUNT ON: the result can say
// success, so count the errors that reach the info callback too
temperature = 95.0f;
server_errors = 0;
const auto er = driver.execute_rpc(
tdsl::string_view{"EXEC dbo.add_reading @device = @p0, @temperature = @p1"}, args);
const bool rejected = not er || server_errors > 0;
if (rejected) {
std::puts("rejected by the procedure");
}
In your own procedures, THROW (SQL Server 2012 and later) is the simpler
choice: it ends the procedure, and the call fails with server_error.
Let a device run only the procedure¶
A login that may only run the procedure can't read or change the tables directly, which limits what a stolen device password can do:
CREATE LOGIN device WITH PASSWORD = '<a long random password>';
CREATE USER device FOR LOGIN device;
GRANT EXECUTE ON dbo.add_reading TO device;
The procedure can still insert into its table: when a procedure and the
tables it uses have the same owner (e.g. both in dbo), SQL Server doesn't
check the caller's permissions on those tables. This is called ownership
chaining.
Related¶
- Run parameterized queries: parameter types and binding
- Read column values
- Handle errors and server messages
- Log sensor readings