---
title: "sql server中bit字段实现取反操作"
author: "yimenghust"
date: "2012-07-20T10:51:44Z"
tags: ["bit", "取反操作"]
categories: ["数据库"]
slug: "sql-server-bit"
draft: false
lastmod: "2012-07-20T10:51:44Z"
id: 1601707
url: "https://yimenghust.iteye.com/blog/1601707"
---

sql server中的bit字段只有两种取值，0或1，在应用程序中可以作为bool值来使用，
直接在sql server中使用“打开表”方法写入的话，填入0或1是非法的，要使用true或false，但是使用select语句查询出来的对应值是1或0.

下面综合介绍几种改变bit字段值的方法：

1.使用取反操作符
update t1 set c1=~c1;

2.使用异或操作符
update t1 set c1=c1^1;

3.使用算术方法实现
update t1 set c1=(c1+1)%2;
或者
update t1 set c1=abs(c1-1);

4.case when语句
update tableName set state=
(case state when 0 then 1 when 1 then 0 else 0 end);


其他数据库实现方法：
access：
UPDATE ywx_subject SET iscurrent =iif(iscurrent,0,1);
这个语句是将数据库中的iscurrent逻辑字段取反 true改为false,false改为true

达梦：
update t1 set c1=c1^1;