如何在Where子句中使用List参数执行ExecuteNonQuery

时间:2014-04-03 00:36:58

标签: c# sql ado.net executenonquery

我的代码如下所示:

var settings = ConfigurationManager.ConnectionStrings["InsurableRiskDB"];
            string server = ConfigurationManager.AppSettings["Server"];
            string cs = String.Format(ConfigurationManager.AppSettings[settings.ProviderName], ConfigurationManager.AppSettings[server]);
            SqlConnection connection = new SqlConnection(cs);

            string PolicyKeys = "";
            for (int i = 0; i < keys.Count(); i++)
            {
                if (i == keys.Count() - 1)
                    PolicyKeys += keys[i] ;
                else
                    PolicyKeys += keys[i] + ", ";
            }

            //have to change the code to pull the user's NBK.
            string user = "'DATALOAD'";
            const string updateQuery = @"UPDATE [InsurableRisk].[dbo].[Policy]
                                         SET [InsuranceCarrierKey] = @ToKey
                                              ,[AuditUser] = @User
                                              ,[AuditDate] = SYSDATETIME()
                                         WHERE PolicyKey in (@PolicyKeys) and InsuranceCarrierKey = @FromKey";
            using (connection)
            {
                using (SqlCommand dataCommand = new SqlCommand(updateQuery, connection))
                {
                    dataCommand.Parameters.AddWithValue("@ToKey", toKey);
                    dataCommand.Parameters.AddWithValue("@User", user);
                    dataCommand.Parameters.AddWithValue("@PolicyKeys", PolicyKeys);
                    dataCommand.Parameters.AddWithValue("@FromKey", fromKey);

                    connection.Open();
                    dataCommand.ExecuteNonQuery();
                    connection.Close();
                }
            }
            res = true;        
        }
        catch (Exception ex)
        {
            MessageBox.Show("There is an error while try in save the changes " + ex.Message, "Error Message", MessageBoxButtons.OKCancel);
            res = false;
        }
        return res;

现在,当我运行此代码时,它表示查询无法执行。抛出异常,它无法将NVarchar转换为int变量@PolicyKeys

enter image description here

有关此代码中缺少的内容的任何建议吗?

1 个答案:

答案 0 :(得分:2)

通常,在SQL中你会写一个IN语句,如下所示:

WHERE SomeColumn IN ('A', 'B', 'C')

你正在做的是在SQL中相当于这个(这不起作用):

WHERE SomeColumn IN ('A, B, C')

相应地更改SQL声明:(从this answer修改)

WHERE PolicyKey in ({0})

然后在循环中添加参数,如下所示:

var parameters = new string[keys.Count()];
for (int i = 0; i < keys.Count(); i++)
{
    parameters[i] = string.Format("@Key{0}", i);
    cmd.Parameters.AddWithValue(parameters[i], keys[i]);
}

cmd.CommandText = string.Format(updateQuery, string.Join(", ", parameters));