如何以编程方式优化,执行多个SELECT查询?

时间:2016-09-01 02:34:09

标签: c# .net sql-server sql-server-2012

提前致谢,如果已经涵盖,请致歉。

以下是未经优化(且不安全)的方法示例:

        string[] ExampleInput = { "foo", "bar", "daily", "special" };
        int[] ReturnData = new int[ExampleInput.GetUpperBound(0)];

        SqlConnection sqlConnection1 = new SqlConnection("FooBar Connection String");
        SqlCommand cmd = new SqlCommand();
        SqlDataReader reader;

        cmd.CommandType = CommandType.Text;
        cmd.Connection = sqlConnection1;

        for (int i = 0; i <= ExampleInput.GetUpperBound(0); i++)
        {
            cmd.CommandText = "SELECT [int] FROM [table] WHERE [string] = '" + ExampleInput[i] + "'; ";
            sqlConnection1.Open();
            reader = cmd.ExecuteReader();

            if (reader.HasRows)
            {
                while (reader.Read())
                    ReturnData[i] = reader.GetInt32(0);
            }

            reader.Close();
            sqlConnection1.Close();
        }

2 个答案:

答案 0 :(得分:0)

您可以对查询执行IN运算符,以便执行单个查询的示例。我对您的代码进行了一些更改,以便将using块用于实现IDisposable接口(从内存中删除)的非托管对象。样本(见评论):

var ExampleInput = { "foo", "bar", "daily", "special" };
List<int> tempReturnData = new List<int>();

using (var sqlConnection1 = new SqlConnection("FooBar Connection String"))
{
    using (var cmd = new SqlCommand()) 
    {
        cmd.Connection = sqlConnection1;

        // generate something like 'foo','bar','daily', 'special' into the string
        string parameterValue = string.Concat("'", string.Join("','", ExampleInput), "'");

        // execute the single query
        cmd.CommandText = string.Format("SELECT [int] FROM [table] WHERE [string] IN ({0});",  parameterValue);

        sqlConnection1.Open();

        using (var reader = cmd.ExecuteReader()) 
        {
            // add all ements on the listof integers
            while (reader.Read())
                tempReturnData.Add(reader.GetInt32(0));        
        }

        reader.Close();
        sqlConnection1.Close();
    }
}

// get the final list of ints as array
int[] ReturnData = tempReturnData.ToArray();

答案 1 :(得分:0)

有多种方法可以运行多个查询并获得结果。您的问题中包含的方法是一种方法,但我建议您保持连接打开并只生成新命令。

由于SqlConnectionSqlCommandSqlDataReader对象是一次性的,因此您应该使用using子句正确处理这些对象。处理这些对象将处理任何非托管资源的清理,并将关闭必要的组件。

以下是基于您现有方法的更新代码。

string[] ExampleInput = { "foo", "bar", "daily", "special" };
int[] ReturnData = new int[ExampleInput.GetUpperBound(0)];

using (SqlConnection sqlConnection1 = new SqlConnection("FooBar Connection String")) 
{
    sqlConnection1.Open();

    for (int i = 0; i <= ExampleInput.GetUpperBound(0); i++)
    {         
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandType = CommandType.Text;
            cmd.Connection = sqlConnection1;
            cmd.CommandText = "SELECT [int] FROM [table] WHERE [string] = '" + ExampleInput[i] + "'; ";

            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                    ReturnData[i] = reader.GetInt32(0);
            }
        }            
    }
}

或者,您可以将查询连接到单个字符串中,并使用SqlDataReader的NextResult方法。

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.nextresult%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396