SQL SERVER: HOW TO TOGGLE / FLIP / INVERT VALUE OF BIT COLUMN

文章介绍了在SQLSERVER中如何切换BIT列的值,提供了多种方法,如使用位运算符、IIF函数和CASE语句。示例中展示了创建一个员工表并插入数据,然后演示了不同方式更新IsActive列,实现值的反转。
摘要由CSDN通过智能技术生成

SQL SERVER: HOW TO TOGGLE / FLIP / INVERT VALUE OF BIT COLUMN

In previous articles I have explained How to Generate row number/serial number without ordering by any columns and Row_number(), rank(), dense_rank(), ntile() ranking functions and Using merge in sql server to insert, update and delete in single statement and CTE recursive query to get parent child hierarchy with levels and Function to check column exists in table or not

Implementation: Let’s create a dummy table for demonstration purpose using the following script.

CREATE TABLE dbo.tbEmployeeMaster
(
EmployeeId INT IDENTITY(1,1) PRIMARY KEY,
Name VARCHAR(100),
Age INT,
IsActive BIT
)

–Insert some dummy data into the table

GO
INSERT INTO dbo.tbEmployeeMaster
VALUES
(‘Aman’,28,1),
(‘Rohan’,34,0),
(‘Varun’,25,1),
(‘Arjun’,45,1),
(‘Raghav’,33,0),
(‘Sameer’,27,0);

–Check data in table
SELECT * FROM dbo.tbEmployeeMaster

在这里插入图片描述

Now lets toggle or flip IsActive column value using various ways:

Toggle Bit Value

SELECT
IsActive,
~IsActive AS IsActive,
ABS ( IsActive-1) AS IsActive,
IsActive ^ 1 AS IsActive,
IsActive=1-IsActive,
IsActive=IIF(IsActive=1,0,1),
CASE IsActive WHEN 1 THEN 0 ELSE 1 END AS IsActive
FROM dbo.tbEmployeeMaster

Note : IIF function will work only in sql 2012 or upper version and it returns a value if a condition is TRUE or another value if a condition is FALSE.

在这里插入图片描述

As we can see Actual value is in First column and in all other columns value is inverted.

Now let’s see how to use this while updating in table . You can use any of the following Update query to update toggled value in table.

UPDATE dbo.tbEmployeeMaster
SET IsActive = ~IsActive
UPDATE dbo.tbEmployeeMaster
SET IsActive = ABS( IsActive-1)
UPDATE dbo.tbEmployeeMaster
SET IsActive = IsActive ^ 1
UPDATE dbo.tbEmployeeMaster
SET IsActive = 1-IsActive
UPDATE dbo.tbEmployeeMaster
SET IsActive=IIF(IsActive=1,0,1)
UPDATE dbo.tbEmployeeMaster
SET IsActive = CASE WHEN IsActive = 1 THEN 0 ELSE 1 END

Result will be as:
在这里插入图片描述

As we can see all values in IsActive column is inverted.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值