SQL Server: IF EXISTS ; ELSE SQL Server: IF EXISTS ; ELSE sql sql

SQL Server: IF EXISTS ; ELSE


EDIT

I want to add the reason that your IF statement seems to not work. When you do an EXISTS on an aggregate, it's always going to be true. It returns a value even if the ID doesn't exist. Sure, it's NULL, but its returning it. Instead, do this:

if exists(select 1 from table where id = 4)

and you'll get to the ELSE portion of your IF statement.


Now, here's a better, set-based solution:

update b  set code = isnull(a.value, 123)from #b bleft join (select id, max(value) from #a group by id) a  on b.id = a.idwhere  b.id = yourid

This has the benefit of being able to run on the entire table rather than individual ids.


Try this:

Update TableB Set  Code = Coalesce(    (Select Max(Value)    From TableA     Where Id = b.Id), 123)From TableB b


I know its been a while since the original post but I like using CTE's and this worked for me:

WITH cte_table_aAS(    SELECT [id] [id]    , MAX([value]) [value]    FROM table_a    GROUP BY [id])UPDATE table_bSET table_b.code = CASE WHEN cte_table_a.[value] IS NOT NULL THEN cte_table_a.[value] ELSE 124 ENDFROM table_bLEFT OUTER JOIN  cte_table_aON table_b.id = cte_table_a.id