Link to home
Start Free TrialLog in
Avatar of kvnsdr
kvnsdr

asked on

If Statement Using Select Update Set?

I'm setting up flip-flop click event that needs to check or uncheck an SQL 'bit' column, however it's not working.

[code]
If (Select col_Num From table1 Where col_Num = '101')
Begin
Update table1 SET col_Bit = 'True'
End
Else
Begin
Update table1 SET col_Bit = 'False'
End
Avatar of Ted Bouskill
Ted Bouskill
Flag of Canada image

If EXISTS(Select col_Num From table1 Where col_Num = '101')
Begin
    Update table1 SET col_Bit = 'True'
End
Else
Begin
    Update table1 SET col_Bit = 'False'
End
Update table1
SET col_Bit = CASE WHEN col_Num = '101' THEN 1 ELSE 0 END

[SQL bit-type columns use 0/1, not 'true'/'false' (nor 0/-1).]
Avatar of kvnsdr
kvnsdr

ASKER

I don't know what to think because my table clearly has True or False in the Bit type column.

Thanks I'll try your advice and get back to you....
Avatar of kvnsdr

ASKER

Problem:

Both examples set 'every row' in the bit column to True, the back to False when I run the code again.

The row with matching '101' data is set as well as every row in the table...
are u using SQL server 6.5 or 7.0, I found the similar problems on these versions
update table1
   set col_Bit = case when col_Num = '101' then 1 else 0 end

(1) You're right... bits show as "True" or "False" in the grid display, but they're stored as 1 or 0, and those are the values you must use to update a bit column.
(2) The above statement updates the col_Bit to True (1) if the same row has a col_Num of 101, otherwise it sets col_Bit to False (0).
I just noticed... this is the same as Scott Pletcher's solution.  Use 1 and 0 (not "true" and "false") and I think you'll see that it works just fine.
Avatar of kvnsdr

ASKER


It still makes changes on all the other rows in the table.

I just want to flip-flop (toggle) one row.
You need to give us a predicate for the where clause on the update statement to restrict it to one row.
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial