UPDATE syntax problem

From: MT <mt(at)open2web(dot)com>
To: pgsql-general <pgsql-general(at)postgresql(dot)org>
Cc: Carlos Moreno <moreno(at)mochima(dot)com>
Subject: UPDATE syntax problem
Date: 2002-12-07 19:32:48
Message-ID: 3DF24CE0.4010000@open2web.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi,

I'm developing a C++ script to update postgresql database records. The
user interacts with the script via an html form. That is, the user is
presented with the data from a particular record in an html form and
asked to update any number of fields in that record.

To perform a multiple column update in postgres one does:

UPDATE tablename
SET column1 = 'blahblah',
column2 = 'moreblahblah',
column3 = 1234
WHERE id = 555;

Here's an excerpt from the script:

//sql statement
string sql;

sql = "UPDATE product SET ";

if (param["new_catid"] != param["old_catid"])
{
sql += "catid = " + param["new_catid"] + ",";
}
else if (param["new_catname"] != param["old_catname"])
{
sql += "prodname = '" + param["new_catname"] + "',";
}
else if (param["new_unitcnt"] != param["old_unitcnt"])
{
sql += "unitcnt = '" + param["new_unitcnt"] + "',";
}
else if (param["new_wprice"] != param["old_wprice"])
{
sql += "wprice = " + param["new_wprice"];
}

sql += "WHERE prodid = '" + param["prodid"] + "'";

int res = conn.Exec (sql.c_str()); //sql exec

Now the problem occurs when a user only wants to update certain columns,
which creates a syntax problem due to the comma (","). In other words
you cannot end a multiple column UPDATE statement with a comma followed by:

WHERE prodid = 'xyz';

Now I could probably solve this problem by building separate UPDATE
statements as such:

if (param["new_catid"] != param["old_catid"])
{
sql = "UPDATE product SET ";
sql += "catid = " + param["new_catid"];
sql += "WHERE prodid = '" + param["prodid"] + "'";
int res = conn.Exec (sql.c_str()); //sql exec
}
else if (param["new_catname"] != param["old_catname"])
{
sql = "UPDATE product SET ";
sql += "prodname = '" + param["new_catname"] + "'";
sql += "WHERE prodid = '" + param["prodid"] + "'";
int res = conn.Exec (sql.c_str()); //sql exec
}

This necessitates calling the database each time the if statement is
true. Is there perhaps a more efficient way of doing this? I'm assuming
that the fewer times you call the database the faster the program will run.

Thanks,

Mark Tessier

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Doug McNaught 2002-12-07 20:07:28 Re: UPDATE syntax problem
Previous Message Neil Conway 2002-12-07 18:45:39 doc fix for OS/X (was: 7.3 on OS X HOWTO)