- private SqlCommand CreateUpdateCommand ()
- {
- // If no table was found, then we can't do an update
- if (QuotedTableName == String.Empty)
- return null;
-
- CreateNewCommand (ref updateCommand);
-
- string command = String.Format ("UPDATE {0} SET ", QuotedTableName);
- StringBuilder columns = new StringBuilder ();
- StringBuilder whereClause = new StringBuilder ();
- int parmIndex = 1;
- string dsColumnName = String.Empty;
- bool keyFound = false;
-
- // First, create the X=Y list for UPDATE
- foreach (DataRow schemaRow in dbSchemaTable.Rows) {
- if (!IncludedInUpdate (schemaRow))
- continue;
- if (columns.Length > 0)
- columns.Append (", ");
-
- SqlParameter parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
- parameter.SourceVersion = DataRowVersion.Current;
-
- columns.Append (String.Format ("{0} = {1}", GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
- }
-
- // Now, create the WHERE clause. This may be optimizable, but it would be ugly to incorporate
- // into the loop above. "Premature optimization is the root of all evil." -- Knuth
- foreach (DataRow schemaRow in dbSchemaTable.Rows) {
- if ((bool)schemaRow["IsExpression"] == true)
- continue;
-
- if (!IncludedInWhereClause (schemaRow))
- continue;
-
- if (whereClause.Length > 0)
- whereClause.Append (" AND ");
-
- bool isKey = (bool) schemaRow ["IsKey"];
- SqlParameter parameter = null;
-
-
- if (isKey)
- keyFound = true;
-
- //ms.net 1.1 generates the null check for columns even if AllowDBNull is false
- //while ms.net 2.0 does not. Anyways, since both forms are logically equivalent
- //following the 2.0 approach
- bool allowNull = (bool) schemaRow ["AllowDBNull"];
- if (!isKey && allowNull) {
- parameter = updateCommand.Parameters.Add (String.Format ("@p{0}", parmIndex++),
- SqlDbType.Int);
- parameter.Value = 1;
- whereClause.Append ("(");
- whereClause.Append (String.Format (clause1, parameter.ParameterName,
- GetQuotedString ((string) schemaRow ["BaseColumnName"])));
- whereClause.Append (" OR ");
- }
-
- parameter = updateCommand.Parameters.Add (CreateParameter (parmIndex++, schemaRow));
- parameter.SourceVersion = DataRowVersion.Original;
-
- whereClause.Append (String.Format (clause2, GetQuotedString (parameter.SourceColumn), parameter.ParameterName));
-
- if (!isKey && allowNull)
- whereClause.Append (")");
- }
- if (!keyFound)
- throw new InvalidOperationException ("Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.");
-
- // We're all done, so bring it on home
- string sql = String.Format ("{0}{1} WHERE ({2})", command, columns.ToString (), whereClause.ToString ());
- updateCommand.CommandText = sql;
- return updateCommand;
- }