将动态参数和值列表传递给C#方法以执行SQL存储过程

时间:2016-01-25 23:10:55

标签: c# .net ssis

我在C#中有一个方法来执行存储过程。这将从SSIS 2014中的脚本组件调用(它还调用Web服务获取数据)。我希望能够传递SQL参数和值的动态列表。我正在考虑使用数组(string [,]),但实际上我认为它更像是一个键值对,因为我真的只需要2列。

有更好/更清洁的方法吗?

这是我到目前为止(半工作的.NET小提琴示例here):

using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;

public class Program
{
    public static void Main()
    {

        // Code for getting data from web service goes here.

        string[,] paramsArray = new string[,]
        {
            {"@ShipmentId", "123456"},
            {"@TransDate", "2016-01-25"},
            {"@FromLocation", "123"},
            {"@ToLocation", "456"},
            {"@Status", "Delivered"},
            {"@TrackingNo", "1Z456789123"},
            {"@UpdatedAtCarrier", DateTime.Now.ToString()},
        };

        SqlStoredProcedureParamArrayNoReturn("My Connection String", "My_Stored_Proc_To_Run", paramsArray);
    }


    public static void SqlStoredProcedureParamArrayNoReturn(string dbConnection, string procName, string[,] paramArray)
    {
        for (int r = 0; r < paramArray.GetLength(0); r++)
        {
            Console.WriteLine(paramArray[r,0] + " =>  " + paramArray[r,1]);
        }
        if (paramArray.GetLength(1) != 2)
        {
            Console.WriteLine("paramArray has too few/too many columns. Exiting method...");
            System.Diagnostics.Debug.WriteLine("paramArray has too few/too many columns. Exiting method...");
        }

        using (SqlConnection conn = new SqlConnection(dbConnection))
        {
            SqlCommand cmd = new SqlCommand(procName, conn);
            cmd.CommandType = CommandType.StoredProcedure;
            for (int r = 0; r < paramArray.GetLength(0); r++)
            {
                cmd.Parameters.Add(new SqlParameter(paramArray[r, 0], paramArray[r, 1]));
            }
            cmd.Connection.Open();
            cmd.ExecuteNonQuery();
            System.Diagnostics.Debug.WriteLine("SQL Command executed successfully.");
        }
    }
}

0 个答案:

没有答案