Azure SQL input binding for Azure Functions

When a function runs, the Azure SQL input binding retrieves data from a database and passes it to the input parameter of the function.

For information on setup and configuration details, see the overview.

Important

This article uses tabs to support multiple versions of the Node.js programming model. The v4 model is generally available and is designed to have a more flexible and intuitive experience for JavaScript and TypeScript developers. For more details about how the v4 model works, refer to the Azure Functions Node.js developer guide. To learn more about the differences between v3 and v4, refer to the migration guide.

Examples

A C# function can be created by using one of the following C# modes:

  • Isolated worker model: Compiled C# function that runs in a worker process that's isolated from the runtime. Isolated worker process is required to support C# functions running on LTS and non-LTS versions .NET and the .NET Framework.
  • In-process model: Compiled C# function that runs in the same process as the Functions runtime.
  • C# script: Used primarily when you create C# functions in the Azure portal.

More samples for the Azure SQL input binding are available in the GitHub repository.

This section contains the following examples:

The examples refer to a ToDoItem class and a corresponding database table:

namespace AzureSQL.ToDo
{
    public class ToDoItem
    {
        public Guid Id { get; set; }
        public int? order { get; set; }
        public string title { get; set; }
        public string url { get; set; }
        public bool? completed { get; set; }
    }
}
CREATE TABLE dbo.ToDo (
    [Id] UNIQUEIDENTIFIER PRIMARY KEY,
    [order] INT NULL,
    [title] NVARCHAR(200) NOT NULL,
    [url] NVARCHAR(200) NOT NULL,
    [completed] BIT NOT NULL
);

HTTP trigger, get row by ID from query string

The following example shows a C# function that retrieves a single record. The function is triggered by an HTTP request that uses a query string to specify the ID. That ID is used to retrieve a ToDoItem record with the specified query.

Note

The HTTP query string parameter is case-sensitive.

using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Extensions.Sql;
using Microsoft.Azure.Functions.Worker.Http;

namespace AzureSQLSamples
{
    public static class GetToDoItem
    {
        [FunctionName("GetToDoItem")]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "gettodoitem")]
            HttpRequest req,
            [SqlInput(commandText: "select [Id], [order], [title], [url], [completed] from dbo.ToDo where Id = @Id",
                commandType: System.Data.CommandType.Text,
                parameters: "@Id={Query.id}",
                connectionStringSetting: "SqlConnectionString")]
            IEnumerable<ToDoItem> toDoItem)
        {
            return new OkObjectResult(toDoItem.FirstOrDefault());
        }
    }
}

HTTP trigger, get multiple rows from route parameter

The following example shows a C# function that retrieves documents returned by the query. The function is triggered by an HTTP request that uses route data to specify the value of a query parameter. That parameter is used to filter the ToDoItem records in the specified query.

using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Extensions.Sql;
using Microsoft.Azure.Functions.Worker.Http;

namespace AzureSQLSamples
{
    public static class GetToDoItems
    {
        [FunctionName("GetToDoItems")]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "gettodoitems/{priority}")]
            HttpRequest req,
            [SqlInput(commandText: "select [Id], [order], [title], [url], [completed] from dbo.ToDo where [Priority] > @Priority",
                commandType: System.Data.CommandType.Text,
                parameters: "@Priority={priority}",
                connectionStringSetting: "SqlConnectionString")]
            IEnumerable<ToDoItem> toDoItems)
        {
            return new OkObjectResult(toDoItems);
        }
    }
}

HTTP trigger, delete rows

The following example shows a C# function that executes a stored procedure with input from the HTTP request query parameter.

The stored procedure dbo.DeleteToDo must be created on the SQL database. In this example, the stored procedure deletes a single record or all records depending on the value of the parameter.

CREATE PROCEDURE [dbo].[DeleteToDo]
    @Id NVARCHAR(100)
AS
    DECLARE @UID UNIQUEIDENTIFIER = TRY_CAST(@ID AS UNIQUEIDENTIFIER)
    IF @UId IS NOT NULL AND @Id != ''
    BEGIN
        DELETE FROM dbo.ToDo WHERE Id = @UID
    END
    ELSE
    BEGIN
        DELETE FROM dbo.ToDo WHERE @ID = ''
    END

    SELECT [Id], [order], [title], [url], [completed] FROM dbo.ToDo
GO
namespace AzureSQL.ToDo
{
    public static class DeleteToDo
    {
        // delete all items or a specific item from querystring
        // returns remaining items
        // uses input binding with a stored procedure DeleteToDo to delete items and return remaining items
        [FunctionName("DeleteToDo")]
        public static IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "DeleteFunction")] HttpRequest req,
            ILogger log,
            [SqlInput(commandText: "DeleteToDo", commandType: System.Data.CommandType.StoredProcedure, 
                parameters: "@Id={Query.id}", connectionStringSetting: "SqlConnectionString")] 
                IEnumerable<ToDoItem> toDoItems)
        {
            return new OkObjectResult(toDoItems);
        }
    }
}

More samples for the Azure SQL input binding are available in the GitHub repository.

This section contains the following examples:

The examples refer to a ToDoItem class (in a separate file ToDoItem.java) and a corresponding database table:

package com.function;
import java.util.UUID;

public class ToDoItem {
    public UUID Id;
    public int order;
    public String title;
    public String url;
    public boolean completed;

    public ToDoItem() {
    }

    public ToDoItem(UUID Id, int order, String title, String url, boolean completed) {
        this.Id = Id;
        this.order = order;
        this.title = title;
        this.url = url;
        this.completed = completed;
    }
}
CREATE TABLE dbo.ToDo (
    [Id] UNIQUEIDENTIFIER PRIMARY KEY,
    [order] INT NULL,
    [title] NVARCHAR(200) NOT NULL,
    [url] NVARCHAR(200) NOT NULL,
    [completed] BIT NOT NULL
);

HTTP trigger, get multiple rows

The following example shows a SQL input binding in a Java function that is triggered by an HTTP request and reads from a query and returns the results in the HTTP response.

package com.function;

import com.microsoft.azure.functions.HttpMethod;
import com.microsoft.azure.functions.HttpRequestMessage;
import com.microsoft.azure.functions.HttpResponseMessage;
import com.microsoft.azure.functions.HttpStatus;
import com.microsoft.azure.functions.annotation.AuthorizationLevel;
import com.microsoft.azure.functions.annotation.FunctionName;
import com.microsoft.azure.functions.annotation.HttpTrigger;
import com.microsoft.azure.functions.sql.annotation.SQLInput;

import java.util.Optional;

public class GetToDoItems {
    @FunctionName("GetToDoItems")
    public HttpResponseMessage run(
            @HttpTrigger(
                name = "req",
                methods = {HttpMethod.GET},
                authLevel = AuthorizationLevel.ANONYMOUS)
                HttpRequestMessage<Optional<String>> request,
            @SQLInput(
                name = "toDoItems",
                commandText = "SELECT * FROM dbo.ToDo",
                commandType = "Text",
                connectionStringSetting = "SqlConnectionString")
                ToDoItem[] toDoItems) {
        return request.createResponseBuilder(HttpStatus.OK).header("Content-Type", "application/json").body(toDoItems).build();
    }
}

HTTP trigger, get row by ID from query string

The following example shows a SQL input binding in a Java function that is triggered by an HTTP request and reads from a query filtered by a parameter from the query string and returns the row in the HTTP response.

public class GetToDoItem {
    @FunctionName("GetToDoItem")
    public HttpResponseMessage run(
            @HttpTrigger(
                name = "req",
                methods = {HttpMethod.GET},
                authLevel = AuthorizationLevel.ANONYMOUS)
                HttpRequestMessage<Optional<String>> request,
            @SQLInput(
                name = "toDoItems",
                commandText = "SELECT * FROM dbo.ToDo",
                commandType = "Text",
                parameters = "@Id={Query.id}",
                connectionStringSetting = "SqlConnectionString")
                ToDoItem[] toDoItems) {
        ToDoItem toDoItem = toDoItems[0];
        return request.createResponseBuilder(HttpStatus.OK).header("Content-Type", "application/json").body(toDoItem).build();
    }
}

HTTP trigger, delete rows

The following example shows a SQL input binding in a Java function that is triggered by an HTTP request and executes a stored procedure with input from the HTTP request query parameter.

The stored procedure dbo.DeleteToDo must be created on the database. In this example, the stored procedure deletes a single record or all records depending on the value of the parameter.

CREATE PROCEDURE [dbo].[DeleteToDo]
    @Id NVARCHAR(100)
AS
    DECLARE @UID UNIQUEIDENTIFIER = TRY_CAST(@ID AS UNIQUEIDENTIFIER)
    IF @UId IS NOT NULL AND @Id != ''
    BEGIN
        DELETE FROM dbo.ToDo WHERE Id = @UID
    END
    ELSE
    BEGIN
        DELETE FROM dbo.ToDo WHERE @ID = ''
    END

    SELECT [Id], [order], [title], [url], [completed] FROM dbo.ToDo
GO
public class DeleteToDo {
    @FunctionName("DeleteToDo")
    public HttpResponseMessage run(
            @HttpTrigger(
                name = "req",
                methods = {HttpMethod.GET},
                authLevel = AuthorizationLevel.ANONYMOUS)
                HttpRequestMessage<Optional<String>> request,
            @SQLInput(
                name = "toDoItems",
                commandText = "dbo.DeleteToDo",
                commandType = "StoredProcedure",
                parameters = "@Id={Query.id}",
                connectionStringSetting = "SqlConnectionString")
                ToDoItem[] toDoItems) {
        return request.createResponseBuilder(HttpStatus.OK).header("Content-Type", "application/json").body(toDoItems).build();
    }
}

More samples for the Azure SQL input binding are available in the GitHub repository.

This section contains the following examples:

The examples refer to a database table:

CREATE TABLE dbo.ToDo (
    [Id] UNIQUEIDENTIFIER PRIMARY KEY,
    [order] INT NULL,
    [title] NVARCHAR(200) NOT NULL,
    [url] NVARCHAR(200) NOT NULL,
    [completed] BIT NOT NULL
);

HTTP trigger, get multiple rows

The following example shows a SQL input binding that is triggered by an HTTP request and reads from a query and returns the results in the HTTP response.

import { app, HttpRequest, HttpResponseInit, input, InvocationContext } from '@azure/functions';

const sqlInput = input.sql({
    commandText: 'select [Id], [order], [title], [url], [completed] from dbo.ToDo',
    commandType: 'Text',
    connectionStringSetting: 'SqlConnectionString',
});

export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
    context.log('HTTP trigger and SQL input binding function processed a request.');
    const toDoItems = context.extraInputs.get(sqlInput);
    return {
        jsonBody: toDoItems,
    };
}

app.http('httpTrigger1', {
    methods: ['GET'],
    authLevel: 'anonymous',
    extraInputs: [sqlInput],
    handler: httpTrigger1,
});
const { app, input } = require('@azure/functions');

const sqlInput = input.sql({
    commandText: 'select [Id], [order], [title], [url], [completed] from dbo.ToDo',
    commandType: 'Text',
    connectionStringSetting: 'SqlConnectionString',
});

app.http('httpTrigger1', {
    methods: ['GET'],
    authLevel: 'anonymous',
    extraInputs: [sqlInput],
    handler: (request, context) => {
        context.log('HTTP trigger and SQL input binding function processed a request.');
        const toDoItems = context.extraInputs.get(sqlInput);
        return {
            jsonBody: toDoItems,
        };
    },
});

HTTP trigger, get row by ID from query string

The following example shows a SQL input binding that is triggered by an HTTP request and reads from a query filtered by a parameter from the query string and returns the row in the HTTP response.

import { app, HttpRequest, HttpResponseInit, input, InvocationContext } from '@azure/functions';

const sqlInput = input.sql({
    commandText: 'select [Id], [order], [title], [url], [completed] from dbo.ToDo where Id = @Id',
    commandType: 'Text',
    parameters: '@Id={Query.id}',
    connectionStringSetting: 'SqlConnectionString',
});

export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
    context.log('HTTP trigger and SQL input binding function processed a request.');
    const toDoItem = context.extraInputs.get(sqlInput);
    return {
        jsonBody: toDoItem,
    };
}

app.http('httpTrigger1', {
    methods: ['GET'],
    authLevel: 'anonymous',
    extraInputs: [sqlInput],
    handler: httpTrigger1,
});
const { app, input } = require('@azure/functions');

const sqlInput = input.sql({
    commandText: 'select [Id], [order], [title], [url], [completed] from dbo.ToDo where Id = @Id',
    commandType: 'Text',
    parameters: '@Id={Query.id}',
    connectionStringSetting: 'SqlConnectionString',
});

app.http('httpTrigger1', {
    methods: ['GET'],
    authLevel: 'anonymous',
    extraInputs: [sqlInput],
    handler: (request, context) => {
        context.log('HTTP trigger and SQL input binding function processed a request.');
        const toDoItem = context.extraInputs.get(sqlInput);
        return {
            jsonBody: toDoItem,
        };
    },
});

HTTP trigger, delete rows

The following example shows a SQL input binding that is triggered by an HTTP request and executes a stored procedure with input from the HTTP request query parameter.

The stored procedure dbo.DeleteToDo must be created on the database. In this example, the stored procedure deletes a single record or all records depending on the value of the parameter.

CREATE PROCEDURE [dbo].[DeleteToDo]
    @Id NVARCHAR(100)
AS
    DECLARE @UID UNIQUEIDENTIFIER = TRY_CAST(@ID AS UNIQUEIDENTIFIER)
    IF @UId IS NOT NULL AND @Id != ''
    BEGIN
        DELETE FROM dbo.ToDo WHERE Id = @UID
    END
    ELSE
    BEGIN
        DELETE FROM dbo.ToDo WHERE @ID = ''
    END

    SELECT [Id], [order], [title], [url], [completed] FROM dbo.ToDo
GO
import { app, HttpRequest, HttpResponseInit, input, InvocationContext } from '@azure/functions';

const sqlInput = input.sql({
    commandText: 'DeleteToDo',
    commandType: 'StoredProcedure',
    parameters: '@Id={Query.id}',
    connectionStringSetting: 'SqlConnectionString',
});

export async function httpTrigger1(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
    context.log('HTTP trigger and SQL input binding function processed a request.');
    const toDoItems = context.extraInputs.get(sqlInput);
    return {
        jsonBody: toDoItems,
    };
}

app.http('httpTrigger1', {
    methods: ['GET'],
    authLevel: 'anonymous',
    extraInputs: [sqlInput],
    handler: httpTrigger1,
});
const { app, input } = require('@azure/functions');

const sqlInput = input.sql({
    commandText: 'DeleteToDo',
    commandType: 'StoredProcedure',
    parameters: '@Id={Query.id}',
    connectionStringSetting: 'SqlConnectionString',
});

app.http('httpTrigger1', {
    methods: ['GET'],
    authLevel: 'anonymous',
    extraInputs: [sqlInput],
    handler: (request, context) => {
        context.log('HTTP trigger and SQL input binding function processed a request.');
        const toDoItems = context.extraInputs.get(sqlInput);
        return {
            jsonBody: toDoItems,
        };
    },
});

More samples for the Azure SQL input binding are available in the GitHub repository.

This section contains the following examples:

The examples refer to a database table:

CREATE TABLE dbo.ToDo (
    [Id] UNIQUEIDENTIFIER PRIMARY KEY,
    [order] INT NULL,
    [title] NVARCHAR(200) NOT NULL,
    [url] NVARCHAR(200) NOT NULL,
    [completed] BIT NOT NULL
);

HTTP trigger, get multiple rows

The following example shows a SQL input binding in a function.json file and a PowerShell function that is triggered by an HTTP request and reads from a query and returns the results in the HTTP response.

The following is binding data in the function.json file:

{
    "authLevel": "anonymous",
    "type": "httpTrigger",
    "direction": "in",
    "name": "req",
    "methods": [
        "get"
    ]
},
{
    "type": "http",
    "direction": "out",
    "name": "res"
},
{
    "name": "todoItems",
    "type": "sql",
    "direction": "in",
    "commandText": "select [Id], [order], [title], [url], [completed] from dbo.ToDo",
    "commandType": "Text",
    "connectionStringSetting": "SqlConnectionString"
}

The configuration section explains these properties.

The following is sample PowerShell code for the function in the run.ps1 file:

using namespace System.Net

param($Request, $todoItems)

Write-Host "PowerShell function with SQL Input Binding processed a request."

Push-OutputBinding -Name res -Value ([HttpResponseContext]@{
    StatusCode = [System.Net.HttpStatusCode]::OK
    Body = $todoItems
})

HTTP trigger, get row by ID from query string

The following example shows a SQL input binding in a PowerShell function that is triggered by an HTTP request and reads from a query filtered by a parameter from the query string and returns the row in the HTTP response.

The following is binding data in the function.json file:

{
    "authLevel": "anonymous",
    "type": "httpTrigger",
    "direction": "in",
    "name": "req",
    "methods": [
        "get"
    ]
},
{
    "type": "http",
    "direction": "out",
    "name": "res"
},
{
    "name": "todoItem",
    "type": "sql",
    "direction": "in",
    "commandText": "select [Id], [order], [title], [url], [completed] from dbo.ToDo where Id = @Id",
    "commandType": "Text",
    "parameters": "@Id = {Query.id}",
    "connectionStringSetting": "SqlConnectionString"
}

The configuration section explains these properties.

The following is sample PowerShell code for the function in the run.ps1 file:

using namespace System.Net

param($Request, $todoItem)

Write-Host "PowerShell function with SQL Input Binding processed a request."

Push-OutputBinding -Name res -Value ([HttpResponseContext]@{
    StatusCode = [System.Net.HttpStatusCode]::OK
    Body = $todoItem
})

HTTP trigger, delete rows

The following example shows a SQL input binding in a function.json file and a PowerShell function that is triggered by an HTTP request and executes a stored procedure with input from the HTTP request query parameter.

The stored procedure dbo.DeleteToDo must be created on the database. In this example, the stored procedure deletes a single record or all records depending on the value of the parameter.

CREATE PROCEDURE [dbo].[DeleteToDo]
    @Id NVARCHAR(100)
AS
    DECLARE @UID UNIQUEIDENTIFIER = TRY_CAST(@ID AS UNIQUEIDENTIFIER)
    IF @UId IS NOT NULL AND @Id != ''
    BEGIN
        DELETE FROM dbo.ToDo WHERE Id = @UID
    END
    ELSE
    BEGIN
        DELETE FROM dbo.ToDo WHERE @ID = ''
    END

    SELECT [Id], [order], [title], [url], [completed] FROM dbo.ToDo
GO
{
    "authLevel": "anonymous",
    "type": "httpTrigger",
    "direction": "in",
    "name": "req",
    "methods": [
        "get"
    ]
},
{
    "type": "http",
    "direction": "out",
    "name": "res"
},
{
    "name": "todoItems",
    "type": "sql",
    "direction": "in",
    "commandText": "DeleteToDo",
    "commandType": "StoredProcedure",
    "parameters": "@Id = {Query.id}",
    "connectionStringSetting": "SqlConnectionString"
}

The configuration section explains these properties.

The following is sample PowerShell code for the function in the run.ps1 file:

using namespace System.Net

param($Request, $todoItems)

Write-Host "PowerShell function with SQL Input Binding processed a request."

Push-OutputBinding -Name res -Value ([HttpResponseContext]@{
    StatusCode = [System.Net.HttpStatusCode]::OK
    Body = $todoItems
})

More samples for the Azure SQL input binding are available in the GitHub repository.

This section contains the following examples:

The examples refer to a database table:

CREATE TABLE dbo.ToDo (
    [Id] UNIQUEIDENTIFIER PRIMARY KEY,
    [order] INT NULL,
    [title] NVARCHAR(200) NOT NULL,
    [url] NVARCHAR(200) NOT NULL,
    [completed] BIT NOT NULL
);

HTTP trigger, get multiple rows

The following example shows a SQL input binding in a function.json file and a Python function that is triggered by an HTTP request and reads from a query and returns the results in the HTTP response.

The following is sample python code for the function_app.py file:

import json
import logging
import azure.functions as func
from azure.functions.decorators.core import DataType

app = func.FunctionApp()

@app.function_name(name="GetToDo")
@app.route(route="gettodo")
@app.sql_input(arg_name="todo",
                        command_text="select [Id], [order], [title], [url], [completed] from dbo.ToDo",
                        command_type="Text",
                        connection_string_setting="SqlConnectionString")
def get_todo(req: func.HttpRequest, todo: func.SqlRowList) -> func.HttpResponse:
    rows = list(map(lambda r: json.loads(r.to_json()), todo))

    return func.HttpResponse(
        json.dumps(rows),
        status_code=200,
        mimetype="application/json"
    )

HTTP trigger, get row by ID from query string

The following example shows a SQL input binding in a Python function that is triggered by an HTTP request and reads from a query filtered by a parameter from the query string and returns the row in the HTTP response.

The following is sample python code for the function_app.py file:

import json
import logging
import azure.functions as func
from azure.functions.decorators.core import DataType

app = func.FunctionApp()

@app.function_name(name="GetToDo")
@app.route(route="gettodo/{id}")
@app.sql_input(arg_name="todo",
                        command_text="select [Id], [order], [title], [url], [completed] from dbo.ToDo where Id = @Id",
                        command_type="Text",
                        parameters="@Id={id}",
                        connection_string_setting="SqlConnectionString")
def get_todo(req: func.HttpRequest, todo: func.SqlRowList) -> func.HttpResponse:
    rows = list(map(lambda r: json.loads(r.to_json()), todo))

    return func.HttpResponse(
        json.dumps(rows),
        status_code=200,
        mimetype="application/json"
    )

HTTP trigger, delete rows

The following example shows a SQL input binding in a function.json file and a Python function that is triggered by an HTTP request and executes a stored procedure with input from the HTTP request query parameter.

The stored procedure dbo.DeleteToDo must be created on the database. In this example, the stored procedure deletes a single record or all records depending on the value of the parameter.

CREATE PROCEDURE [dbo].[DeleteToDo]
    @Id NVARCHAR(100)
AS
    DECLARE @UID UNIQUEIDENTIFIER = TRY_CAST(@ID AS UNIQUEIDENTIFIER)
    IF @UId IS NOT NULL AND @Id != ''
    BEGIN
        DELETE FROM dbo.ToDo WHERE Id = @UID
    END
    ELSE
    BEGIN
        DELETE FROM dbo.ToDo WHERE @ID = ''
    END

    SELECT [Id], [order], [title], [url], [completed] FROM dbo.ToDo
GO

The following is sample python code for the function_app.py file:

import json
import logging
import azure.functions as func
from azure.functions.decorators.core import DataType

app = func.FunctionApp()

@app.function_name(name="DeleteToDo")
@app.route(route="deletetodo/{id}")
@app.sql_input(arg_name="todo",
                        command_text="DeleteToDo",
                        command_type="StoredProcedure",
                        parameters="@Id={id}",
                        connection_string_setting="SqlConnectionString")
def get_todo(req: func.HttpRequest, todo: func.SqlRowList) -> func.HttpResponse:
    rows = list(map(lambda r: json.loads(r.to_json()), todo))

    return func.HttpResponse(
        json.dumps(rows),
        status_code=200,
        mimetype="application/json"
    )

Attributes

The C# library uses the SqlAttribute attribute to declare the SQL bindings on the function, which has the following properties:

Attribute property Description
CommandText Required. The Transact-SQL query command or name of the stored procedure executed by the binding.
ConnectionStringSetting Required. The name of an app setting that contains the connection string for the database against which the query or stored procedure is being executed. This value isn't the actual connection string and must instead resolve to an environment variable name.
CommandType Required. A CommandType value, which is Text for a query and StoredProcedure for a stored procedure.
Parameters Optional. Zero or more parameter values passed to the command during execution as a single string. Must follow the format @param1=param1,@param2=param2. Neither the parameter name nor the parameter value can contain a comma (,) or an equals sign (=).

Annotations

In the Java functions runtime library, use the @SQLInput annotation (com.microsoft.azure.functions.sql.annotation.SQLInput) on parameters whose value would come from Azure SQL. This annotation supports the following elements:

Element Description
commandText Required. The Transact-SQL query command or name of the stored procedure executed by the binding.
connectionStringSetting Required. The name of an app setting that contains the connection string for the database against which the query or stored procedure is being executed. This value isn't the actual connection string and must instead resolve to an environment variable name.
commandType Required. A CommandType value, which is "Text" for a query and "StoredProcedure" for a stored procedure.
name Required. The unique name of the function binding.
parameters Optional. Zero or more parameter values passed to the command during execution as a single string. Must follow the format @param1=param1,@param2=param2. Neither the parameter name nor the parameter value can contain a comma (,) or an equals sign (=).

Configuration

The following table explains the properties that you can set on the options object passed to the input.sql() method.

Property Description
commandText Required. The Transact-SQL query command or name of the stored procedure executed by the binding.
connectionStringSetting Required. The name of an app setting that contains the connection string for the database against which the query or stored procedure is being executed. This value isn't the actual connection string and must instead resolve to an environment variable name. Optional keywords in the connection string value are available to refine SQL bindings connectivity.
commandType Required. A CommandType value, which is Text for a query and StoredProcedure for a stored procedure.
parameters Optional. Zero or more parameter values passed to the command during execution as a single string. Must follow the format @param1=param1,@param2=param2. Neither the parameter name nor the parameter value can contain a comma (,) or an equals sign (=).

Configuration

The following table explains the binding configuration properties that you set in the function.json file.

function.json property Description
type Required. Must be set to sql.
direction Required. Must be set to in.
name Required. The name of the variable that represents the query results in function code.
commandText Required. The Transact-SQL query command or name of the stored procedure executed by the binding.
connectionStringSetting Required. The name of an app setting that contains the connection string for the database against which the query or stored procedure is being executed. This value isn't the actual connection string and must instead resolve to an environment variable name. Optional keywords in the connection string value are available to refine SQL bindings connectivity.
commandType Required. A CommandType value, which is Text for a query and StoredProcedure for a stored procedure.
parameters Optional. Zero or more parameter values passed to the command during execution as a single string. Must follow the format @param1=param1,@param2=param2. Neither the parameter name nor the parameter value can contain a comma (,) or an equals sign (=).

When you're developing locally, add your application settings in the local.settings.json file in the Values collection.

Usage

The attribute's constructor takes the SQL command text, the command type, parameters, and the connection string setting name. The command can be a Transact-SQL (T-SQL) query with the command type System.Data.CommandType.Text or stored procedure name with the command type System.Data.CommandType.StoredProcedure. The connection string setting name corresponds to the application setting (in local.settings.json for local development) that contains the connection string to the Azure SQL or SQL Server instance.

Queries executed by the input binding are parameterized in Microsoft.Data.SqlClient to reduce the risk of SQL injection from the parameter values passed into the binding.

If an exception occurs when a SQL input binding is executed then the function code won't execute. This may result in an error code being returned, such as an HTTP trigger returning a 500 error code.

Next steps