如何向Azure函数传递参数

9

我有一个 Azure 定时器函数,用于将数据从我的本地数据库复制到 Azure 管理的数据库中。目前,我在函数中硬编码了表名。

是否可以将参数作为输入传递给函数,而不是硬编码它们?

public static void Run([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, TraceWriter log) {
            string srcConnection = @"on premises connecting string";
            string destConnection = @"Azure managed instance connection string";

            string srcTable = "SourceTableName"; //am trying to make this as parameter
            string destTable = "DestinationTableName"; //am trying to make this as parameter
            string tmpTable = "select top 0 * into #DestTable from " + destTable;

            using(SqlConnection
                        srcConn = new SqlConnection(srcConnection),
                        destConn = new SqlConnection(destConnection)
                    ) {
                using(SqlCommand
                        srcGetCmd = new SqlCommand(srcTable, srcConn)
                    ) {
                    srcConn.Open();

                    destConn.Open();

                    SqlCommand cmd = new SqlCommand(tmpTable, destConn);
                    cmd.CommandTimeout = 180;
                    cmd.ExecuteNonQuery();
                    log.Info($"Temp table generated at: {DateTime.Now}");

                    SqlDataReader reader = srcGetCmd.ExecuteReader();
                    log.Info($"Source data loaded at: {DateTime.Now}");

                    using(SqlBulkCopy bulk = new SqlBulkCopy(destConn)) {
                        bulk.DestinationTableName = "#DestTable";
                        bulk.WriteToServer(reader);
                    }

                    string mergeSql = @"<sql logic to insert/Update/delete the data>";

                    cmd.CommandText = mergeSql;
                    cmd.CommandTimeout = 180;
                    cmd.ExecuteNonQuery();
                    log.Info($"Data update from temp table to destination at: {DateTime.Now}");

                    //Execute the command to drop temp table
                    cmd = new SqlCommand("drop table #DestTable", destConn);
                    cmd.CommandTimeout = 180;
                    cmd.ExecuteNonQuery();
                    log.Info($"Drop temp table at: {DateTime.Now}");

                    srcConn.Close();
                    destConn.Close();
                }
            }
            log.Info($"C# Timer trigger function executed at: {DateTime.Now}");

        }

如您所见,我已经硬编码了表名,这是否可以作为参数?

1个回答

7

最简单的方法是添加应用程序设置并使用这些名称(例如“SourceTableName”),然后从Environment中获取它们:

string srcTable = Environment.GetEnvironmentVariable("SourceTableName");

如果你真的想把它作为参数使用,你需要创建一个自定义绑定,类似于我在编写Azure函数的自定义绑定中所做的。这可能会有点过度。


谢谢,我会看一下并回复你。 - Pரதீப்

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接