Case Statement in Update Command SQL Server

Problem

I have a table which has a two columns names and status respectively. I have to update status column. If status column contain true then update it with false else update it true.

Solution

Let's create a table and name it NewTable.
  1. CREATE TABLE [dbo].[NewTable](  
  2. [Names] [varchar](50) NULL,  
  3. [status] [bitNULL  
  4. )   
Let's insert some data in table.

For true
  1. declare @i int=0  
  2. while (@i<100)  
  3. begin  
  4. insert into NewTable values('test'+CONVERT(varchar(3), @i)+'',1)  
  5. set @i=@i+1  
  6. end  
For false
  1. declare @i int=100  
  2. while (@i<200)  
  3. begin  
  4. insert into NewTable values('test'+CONVERT(varchar(3), @i)+'',0)  
  5. set @i=@i+1  
  6. end  
Now, I am going to write a query for update.
  1. Update NewTable set status= case status when 1 then 0 when 0 then 1 end  
Run this query and see the output. It works as expected.
 
I hope you enjoy this blog.
Happy coding :)