0

私のコードは次のようになります。

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;

今、このコードを実行すると、クエリを実行できないと表示されます。例外がスローされ、変数 @PolicyKeys の NVarchar を int に変換できません

ここに画像の説明を入力

このコードで何が欠けているかについての提案はありますか?

4

1 に答える 1

2

通常、次のようなステートメントを記述しSQLます。IN

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

あなたがしていることは、SQLでこれと同等です(これは機能しません):

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

SQLそれに応じてステートメントを変更してください:(この回答から変更)

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));
于 2014-04-03T01:26:49.007 に答える