Pregunta

i have 2 tables of the following structure

Table1
Id(long), Name(nvarchar), ValuesExist(bit)

Table2
Id(long), Table1Id(long), Value(int)

with foreign key constraint on Table.Id and Table2.Table1Id

Now i want to update Table1 according to the following logic

if (there are values in Table2 corresponding to a row Table1 AND Atleast one the values is > 0 )
then Table1.ValuesExist = 1
else Table1.ValuesExist = 0

i have looked and tried many examples given on SO abt how to update a column using join but cudnt find any example in which updation is being done through logic or some ComputedColumn

¿Fue útil?

Solución 2

Here is one method. It uses a correlated subquery in the update and is very close to how you stated the problem:

update table1 t1
    set ValuesExist = (case when exists (select 1
                                         from Table2 t2
                                         where t2.Table1Id = t1.Id and t2.Value > 0
                                        )
                            then 1 else 0
                       end);

This will perform best if you have an index on Table2(Table1Id, Value).

Otros consejos

UPDATE T1
SET ValuesExist = 
  CASE 
     WHEN T2.Value > 0 THEN 1
     ELSE 0
  END
FROM Table1 T1
LEFT JOIN Table2 T2 ON T1.Id = T2.Table1Id
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top