开发者

Update table in run time and the column not known in compile time

开发者 https://www.devze.com 2023-04-05 11:14 出处:网络
I am trying to write the SQL to update multiple columns based on some code condition to the table in the code.

I am trying to write the SQL to update multiple columns based on some code condition to the table in the code.

For example, make it the easiest one in two columns

UPDATE table set A = valueA where conditionA..

OR UPDATE table set B=valueB where conditionA..

OR UPDATE table set A=valueA, B=valueB where conditionA..

The condition is the same, but valueA/valueB may not exist depending on the code

Is there any convenient way to combine them to开发者_JAVA技巧gether in one SQL such as the select one WHERE 1=1 and <condition> so that I can add the conditions regardless one or more than one conditions?

Hope it make sense.


if you use the same condition you can write the query simply like this:

UPDATE [table] SET A = valueA, B=valueB, C=valueC WHERE <condition>

But if you need different conditions for all the fields, you could you a CASE operator like this:

UPDATE [table] SET A = CASE WHEN <cond_for_A> THEN valA ELSE A END, 
  CASE WHEN <cond_for_B> THEN valB ELSE B END,
  CASE WHEN <cond_for_C> THEN valC ELSE C END


You vary the fields being updated, presumably based on some condition in your code, which probably means you won't be able to get away with just one SQL statement - bound parameters cannot "add" or "remove" columns within SQL text.

If you have a small number of columns, you can make a separate SQL statement for each combination of them that is of interest. Otherwise, you'll likely need to construct the SQL text dynamically and fill the SET clause of your statement so it includes exactly the columns you need.

None of this should serve as an excuse to skip properly binding all parameters, though!

0

精彩评论

暂无评论...
验证码 换一张
取 消