適用於 Azure Functions 的 Azure SQL 輸入系結

當函式執行時,Azure SQL 輸入系結會從資料庫擷取數據,並將其傳遞至函式的輸入參數。

如需安裝和組態詳細數據的詳細資訊,請參閱概

重要

本文使用索引標籤來支援多個版本的Node.js程序設計模型。 v4 模型已正式推出,旨在為 JavaScript 和 TypeScript 開發人員提供更靈活的直覺式體驗。 如需 v4 模型運作方式的詳細資訊,請參閱 Azure Functions Node.js開發人員指南。 若要深入瞭解 v3 與 v4 之間的差異,請參閱 移轉指南

範例

您可以使用下列其中一種 C# 模式來建立 C# 函式:

  • 隔離的背景工作模型:在與運行時間隔離的背景工作進程中執行的已編譯 C# 函式。 需要隔離的背景工作進程,才能支援在 LTS 和非 LTS 版本 .NET 和 .NET Framework 上執行的 C# 函式。
  • 同進程模型:在與 Functions 運行時間相同的進程中執行的已編譯 C# 函式。
  • C# 文稿:主要用於在 Azure 入口網站 中建立 C# 函式。

重要

支援將於 2026 年 11 月 10 日結束進程模型。 強烈建議您將 應用程式移轉至隔離的背景工作模型 ,以取得完整支援。

Azure SQL 輸入繫結的其他範例可在 GitHub 存放庫中取得。

本區段包含下列範例:

這些範例會參考 ToDoItem 類別和對應的資料庫資料表:

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 觸發程序,依識別碼從查詢字串取得資料列

下列範例顯示擷 取單一記錄的 C# 函式 。 此函式是由 使用查詢字串來指定標識碼的 HTTP 要求 所觸發。 該識別碼用來擷取具有所指定查詢的 ToDoItem 記錄。

注意

HTTP 查詢字串參數會區分大小寫。

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 觸發程式,從路由參數取得多個數據列

下列範例顯示可 擷取查詢所傳回檔的 C# 函 式。 此函式是由 使用路由數據來指定查詢參數值的 HTTP 要求 所觸發。 該參數用來篩選 ToDoItem 指定查詢中的記錄。

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 觸發程序,刪除資料列

下列範例示範 C # 函 式,其會使用 HTTP 要求查詢參數的輸入來執行預存程式。

必須在 SQL 資料庫上建立預存程式 dbo.DeleteToDo。 在此範例中,預存程式會刪除單一記錄或所有記錄,取決於參數的值。

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);
        }
    }
}

Azure SQL 輸入繫結的其他範例可在 GitHub 存放庫中取得。

本區段包含下列範例:

這些範例會參考類別 ToDoItem (在不同的檔案 ToDoItem.java中)和對應的資料庫資料表:

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 觸發程式,取得多個數據列

下列範例示範由 HTTP 要求觸發的 Java 函式中的 SQL 輸入系結,並從查詢讀取,並在 HTTP 回應中傳回結果。

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 觸發程序,依識別碼從查詢字串取得資料列

下列範例示範由 HTTP 要求觸發的 Java 函式中的 SQL 輸入系結,並從查詢字串中由參數篩選的查詢讀取,並傳回 HTTP 回應中的數據列。

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 觸發程序,刪除資料列

下列範例示範由 HTTP 要求觸發的 Java 函 式中的 SQL 輸入系結,並使用來自 HTTP 要求查詢參數的輸入來執行預存程式。

必須在資料庫上建立預存程式 dbo.DeleteToDo 。 在此範例中,預存程式會刪除單一記錄或所有記錄,取決於參數的值。

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();
    }
}

Azure SQL 輸入繫結的其他範例可在 GitHub 存放庫中取得。

本區段包含下列範例:

這些範例會參考資料庫資料表:

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 觸發程式,取得多個數據列

下列範例顯示由 HTTP 要求觸發的 SQL 輸入系結,並從查詢讀取,並在 HTTP 回應中傳回結果。

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 觸發程序,依識別碼從查詢字串取得資料列

下列範例顯示由 HTTP 要求觸發的 SQL 輸入系結,並從查詢字串參數篩選的查詢讀取,並傳回 HTTP 回應中的數據列。

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 觸發程序,刪除資料列

下列範例示範由 HTTP 要求觸發的 SQL 輸入系結,並使用來自 HTTP 要求查詢參數的輸入來執行預存程式。

必須在資料庫上建立預存程式 dbo.DeleteToDo 。 在此範例中,預存程式會刪除單一記錄或所有記錄,取決於參數的值。

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,
        };
    },
});

Azure SQL 輸入繫結的其他範例可在 GitHub 存放庫中取得。

本區段包含下列範例:

這些範例會參考資料庫資料表:

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 觸發程式,取得多個數據列

下列範例示範 function.json 檔案中的 SQL 輸入系結,以及由 HTTP 要求觸發的 PowerShell 函式,並從查詢讀取,並在 HTTP 回應中傳回結果。

以下是 function.json 檔案中的繫結資料:

{
    "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"
}

區段說明這些屬性。

以下是 檔案中函式的 run.ps1 範例 PowerShell 程式代碼:

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 觸發程序,依識別碼從查詢字串取得資料列

下列範例示範由 HTTP 要求觸發的 PowerShell 函式中的 SQL 輸入系結,並從查詢字串中由參數篩選的查詢讀取,並傳回 HTTP 回應中的數據列。

以下是 function.json 檔案中的繫結資料:

{
    "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"
}

區段說明這些屬性。

以下是 檔案中函式的 run.ps1 範例 PowerShell 程式代碼:

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 觸發程序,刪除資料列

下列範例示範 function.json 檔案中的 SQL 輸入系結,以及由 HTTP 要求觸發的 PowerShell 函 式,並使用來自 HTTP 要求查詢參數的輸入來執行預存程式。

必須在資料庫上建立預存程式 dbo.DeleteToDo 。 在此範例中,預存程式會刪除單一記錄或所有記錄,取決於參數的值。

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"
}

區段說明這些屬性。

以下是 檔案中函式的 run.ps1 範例 PowerShell 程式代碼:

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
})

Azure SQL 輸入繫結的其他範例可在 GitHub 存放庫中取得。

本區段包含下列範例:

這些範例會參考資料庫資料表:

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 觸發程式,取得多個數據列

下列範例示範 function.json 檔案中的 SQL 輸入系結,以及由 HTTP 要求觸發的 Python 函式,並從查詢讀取,並在 HTTP 回應中傳回結果。

以下是 function.json 檔案中的繫結資料:

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

區段說明這些屬性。

以下是範例 Python 程式代碼:

import azure.functions as func
import json

def main(req: func.HttpRequest, todoItems: func.SqlRowList) -> func.HttpResponse:
    rows = list(map(lambda r: json.loads(r.to_json()), todoItems))

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

HTTP 觸發程序,依識別碼從查詢字串取得資料列

下列範例示範由 HTTP 要求觸發的 Python 函式中的 SQL 輸入系結,並從查詢字串中由參數篩選的查詢讀取,並傳回 HTTP 回應中的數據列。

以下是 function.json 檔案中的繫結資料:

{
    "authLevel": "anonymous",
    "type": "httpTrigger",
    "direction": "in",
    "name": "req",
    "methods": [
        "get"
    ]
},
{
    "type": "http",
    "direction": "out",
    "name": "$return"
},
{
    "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"
}

區段說明這些屬性。

以下是範例 Python 程式代碼:

import azure.functions as func
import json

def main(req: func.HttpRequest, todoItem: func.SqlRowList) -> func.HttpResponse:
    rows = list(map(lambda r: json.loads(r.to_json()), todoItem))

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

HTTP 觸發程序,刪除資料列

下列範例示範function.json檔案中的 SQL 輸入系結,以及由 HTTP 要求觸發的 Python 函 式,並使用來自 HTTP 要求查詢參數的輸入來執行預存程式。

必須在資料庫上建立預存程式 dbo.DeleteToDo 。 在此範例中,預存程式會刪除單一記錄或所有記錄,取決於參數的值。

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": "$return"
},
{
    "name": "todoItems",
    "type": "sql",
    "direction": "in",
    "commandText": "DeleteToDo",
    "commandType": "StoredProcedure",
    "parameters": "@Id = {Query.id}",
    "connectionStringSetting": "SqlConnectionString"
}

區段說明這些屬性。

以下是範例 Python 程式代碼:

import azure.functions as func
import json

def main(req: func.HttpRequest, todoItems: func.SqlRowList) -> func.HttpResponse:
    rows = list(map(lambda r: json.loads(r.to_json()), todoItems))

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

屬性

C# 連結 會使用 SqlAttribute 屬性在函式上宣告 SQL 系結,其具有下列屬性:

Attribute 屬性 描述
CommandText 必要。 系結所執行之預存程式的 Transact-SQL 查詢命令或名稱。
ConnectionStringSetting 必要。 應用程式設定的名稱,其中包含執行查詢或預存程式的資料庫 連接字串。 此值不是實際的 連接字串,必須改為解析為環境變數名稱。
CommandType 必要。 CommandType 值,這是預存程式的查詢文字StoredProcedure
參數 選擇性。 在執行期間,以單一字串的形式傳遞至命令的零個或多個參數值。 必須遵循 格式 @param1=param1,@param2=param2。 參數名稱或參數值都不能包含逗號 (,) 或等號 (=)。

註釋

Java 函式運行時間連結庫中,對值來自 Azure SQL 的參數使用 @SQLInput 註釋 (com.microsoft.azure.functions.sql.annotation.SQLInput)。 此批註支援下列元素:

元素 描述
commandText 必要。 系結所執行之預存程式的 Transact-SQL 查詢命令或名稱。
connectionStringSetting 必要。 應用程式設定的名稱,其中包含執行查詢或預存程式的資料庫 連接字串。 此值不是實際的 連接字串,必須改為解析為環境變數名稱。
commandType 必要。 CommandType 值,這是查詢的 “Text”,預存程式的 “StoredProcedure”。
name 必要。 函式系結的唯一名稱。
parameters 選擇性。 在執行期間,以單一字串的形式傳遞至命令的零個或多個參數值。 必須遵循 格式 @param1=param1,@param2=param2。 參數名稱或參數值都不能包含逗號 (,) 或等號 (=)。

組態

下表說明您可以在傳遞至 input.sql() 方法的物件options上設定的屬性。

屬性 說明
commandText 必要。 系結所執行之預存程式的 Transact-SQL 查詢命令或名稱。
connectionStringSetting 必要。 應用程式設定的名稱,其中包含執行查詢或預存程式的資料庫 連接字串。 此值不是實際的 連接字串,必須改為解析為環境變數名稱。 連接字串 值中的選擇性關鍵詞可用來精簡 SQL 系結連線能力。
commandType 必要。 CommandType 值,這是預存程式的查詢文字StoredProcedure
parameters 選擇性。 在執行期間,以單一字串的形式傳遞至命令的零個或多個參數值。 必須遵循 格式 @param1=param1,@param2=param2。 參數名稱或參數值都不能包含逗號 (,) 或等號 (=)。

組態

下表說明您在 function.json 檔案中設定的繫結設定屬性。

function.json 屬性 描述
type 必要。 必須設定為 sql
direction 必要。 必須設定為 in
name 必要。 代表函式程式代碼中查詢結果的變數名稱。
commandText 必要。 系結所執行之預存程式的 Transact-SQL 查詢命令或名稱。
connectionStringSetting 必要。 應用程式設定的名稱,其中包含執行查詢或預存程式的資料庫 連接字串。 此值不是實際的 連接字串,必須改為解析為環境變數名稱。 連接字串 值中的選擇性關鍵詞可用來精簡 SQL 系結連線能力。
commandType 必要。 CommandType 值,這是預存程式的查詢文字StoredProcedure
parameters 選擇性。 在執行期間,以單一字串的形式傳遞至命令的零個或多個參數值。 必須遵循 格式 @param1=param1,@param2=param2。 參數名稱或參數值都不能包含逗號 (,) 或等號 (=)。

當您在本機開發時,請在集合中的 local.settings.json 檔案Values中新增應用程式設定。

使用方式

屬性的建構函式會採用 SQL 命令文字、命令類型、參數,以及 連接字串 設定名稱。 此命令可以是具有命令型 System.Data.CommandType.Text 別的 Transact-SQL (T-SQL) 查詢,或具有命令類型的 System.Data.CommandType.StoredProcedure預存程序名稱。 連接字串 設定名稱會對應至包含 Azure SQL 或 SQL Server 實例 連接字串 的應用程式設定(用於local.settings.json本機開發)。

輸入系結所執行的查詢會在 Microsoft.Data.SqlClient 中參數化,以降低傳遞至系結的參數值 SQL 插入的風險

如果執行 SQL 輸入系結時發生例外狀況,則函式程式代碼將不會執行。 這可能會導致傳回錯誤碼,例如傳回 500 錯誤碼的 HTTP 觸發程式。

下一步