Docs / Your First SQL Query

Your First SQL Query

What this page covers#

This page shows how to execute SQL text through db.Sql.

The simple version#

MooDb is stored procedure first, but raw SQL is available through the Sql property.

That means SQL text calls look like this:

</> C#
var user = await db.Sql.SingleAsync<User>(
    "SELECT [UserId], [Email], [DisplayName] FROM [dbo].[tbl_User] WHERE [UserId] = @UserId;",
    new MooParams().AddInt("@UserId", 1));

Why there is a separate Sql surface#

The separate Sql surface makes raw SQL explicit in the calling code.

That is useful because it tells the reader straight away:

  • this call is not a stored procedure
  • SQL text is being passed directly
  • the code is intentionally choosing the SQL-text path

Example: read many rows#

</> C#
var users = await db.Sql.ListAsync<User>(
    "SELECT [UserId], [Email], [DisplayName] FROM [dbo].[tbl_User] ORDER BY [UserId];");

Example: execute a SQL update#

</> C#
var rowsAffected = await db.Sql.ExecuteAsync(
    "UPDATE [dbo].[tbl_User] SET [DisplayName] = @DisplayName WHERE [UserId] = @UserId;",
    new MooParams()
        .AddNVarChar("@DisplayName", "Ada Lovelace", 200)
        .AddInt("@UserId", 1));