How to go through each row in the database compare and update a specific column?

2

I have a table named PRODUCT and I need to make a comparison between two columns, the column DATA_INICIAL AND DATA_FINAL , for each line covered, if the product does not agree enter the value 0 in the PROD_ATIVO column.

Rule: If the start date is greater than the current date or the end date is less than the present date the product should not be displayed.

Product (Exemplification) :

Product name: Danoninho
Product display date: 3/27/2017 to 3/30/2017.

    
asked by anonymous 27.03.2017 / 20:53

3 answers

2

In the tags it says it's mysql so you need to run an update in the product table, it would look something like this:

UPDATE produto
SET PROD_ATIVO = 0
WHERE 
DATA_INCIAL > DATE("now")
OR DATA_FINAL < DATE("now");

Here we say: Update all records and change PROD_ATIVE to 0 where the start_date is greater than the current date (mysql date function) or the date_final is less than the current date;

mysql Date Functions: link

EDIT: Assuming the date fields are as timestamp or date, if they are as string there only by converting to dates, the date function does this too ...

    
27.03.2017 / 22:33
3
  

If the DATA_FINAL is already less than the current date, the DATA_INICIAL will never be greater than the current date. So an update in the PROD_ATIVO column is enough when the DATA_FINAL is smaller than the current date.

 Update PRODUTO SET PROD_ATIVO='0' where DATA_FINAL < now()
  

However, if you are not sure that the dates in the database were entered correctly, you can do so

 Update PRODUTO set PROD_ATIVO='0' where DATA_FINAL < now() or Data_INICIAL > now()
    
28.03.2017 / 02:13
0

You need to give UPDATE . At Tutorial Points has a page about it:

Using MySQL:

UPDATE produto
SET PROD_ATIVO =
    CASE
        WHEN DATA_INICIAL <= now() AND DATA_FINAL > now() THEN 1
        ELSE 0
    END

EDIT

As mentioned by @ rock.ownar, the problem is update using multiple tables.

You can check the MySQL syntax for this; also has the alternative of using the second table only in the where clause, such as a subquery .

UPDATE produto, tb_cupons
SET produto.prod_ativo = 0
WHERE
   produto.produto_id = tb_cupons.produto_id AND
   (
       tb_cupons.data_inicial < now() OR
       tb_cupons.data_final > now()
   )
    
27.03.2017 / 21:02