Skip to main content

query_as

Macro query_as 

Source
macro_rules! query_as {
    ($out_struct:path, $query:expr) => { ... };
    ($out_struct:path, $query:expr, $($args:tt)*) => { ... };
}
Available on crate feature macros only.
Expand description

Compile-time checked SQL query for MSSQL via ODBC, mapping to a named struct.

Like query! but deserialises each row into a struct you provide. The struct fields are matched to columns by name and their types are checked against the database schema at compile time.

struct User {
    id: i32,
    name: String,
}

let users = sqlx_mssql_odbc::query_as!(User, "SELECT id, name FROM users")
    .fetch_all(&mut conn)
    .await?;

for user in users {
    println!("{}: {}", user.id, user.name);
}

Combine with the derive feature’s FromRow derive to avoid manually writing struct definitions:

#[derive(Debug, FromRow)]
struct Order {
    id: i32,
    total: rust_decimal::Decimal,
    placed_at: chrono::NaiveDateTime,
}

let orders = sqlx_mssql_odbc::query_as!(Order, "SELECT id, total, placed_at FROM orders")
    .fetch_all(&mut conn)
    .await?;

Requires the macros feature.