The INSERT syntax I’ve been using is this
INSERT INTO TableName VALUES (...)
The UPDATE syntax I’ve been using is
UPDATE TableName SET ColumnName=Value WHERE ...
So in all my code, I have to generate 2 strings, which would result in something like this
insertStr = "(27, 'John Brown', 102)";
updateStr = "ID=27, Name='John Brown', ItemID=102";
and then use them separately
"UPDATE TableName SET " + updateStr + " WHERE ID=27 " +
"IF @@ROWCOUNT=0 "+
"INSERT INTO TableName VALUES (" + insertStr + ")"
It starts bothering me when I am working with tables with like 30 columns.
Can’t we generate just one string to use on both INSERT and UPDATE?
eg. using insertStr above on UPDATE statement or updateStr on INSERT statement, or a whole new way?
Some DBMS’ have an extension to do this but why don’t you just provide a function to do it for you? We’ve actually done this before.
I’m not sure what language you’re using but it’s probably got associative arrays where you can wrote something like:
and, if it doesn’t have associative arrays, you can emulate them with multiple integer-based arrays of strings.
In our
upsert()function, we just constructed a string (update, theninsertif theupdatefailed) and passed it to our DBMS. We kept the primary keys separate from our other fields since that made construction of the update statement a lot easier (primary key columns went in the where clause, other columns were just set).The result of the calls above would result in the following SQL (we had a different check for failed
updatebut I’ve put your@@rowcountin for this example):That’s one solution which worked well for us. No doubt there are others.