Set a column on a populated table to not allow nulls where lots of rows already are set to null

发布于 2022-09-05 15:29:33 字数 1121 浏览 24 评论 0

I've got a table with an active column of type bit that is mostly set to null. The active column was added as an after thought and mistakenly set to allow nulls. So SQL Server won't let me turn off the null flag because most of the fields are already set to null.

I tried setting a default value of 1 to the column and then removing the null flag but it wasn't having any of that. I think the default value only applies to inserts and not an alter.

I then tried to set all the null values to 1 explicitly with the following query:

Update cnc.aidPage set active = 1 where active = null

Unfortunately this doesn't affect any rows. I tried derivatives of this and found that it doesn't change anything only when the filter is trying for null. So the following work:

Update cnc.aidPage set active = 1 where active = 0
Update cnc.aidPage set active = null where active = 1

I would appreciate it if anyone could tell me why the filter doesn't work if I check for null or if there is an easier way to accomplish turning allow nulls off.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

心的憧憬 2022-09-12 15:29:34

NULL isn't a value -- it's a placeholder to indicate the lack of any value, so you can't use math operators to check for it. You need to use:

UPDATE cnc.aidPage 
   SET active = 1 
 WHERE active IS NULL
无边思念无边月 2022-09-12 15:29:34

Your problem is that "null" in most SQL implementations, unlike most imperative languages, doesn't "equal" anything. NULL doesn't even equal NULL explicitly. You have to use the special "is" operator to do null checks:

Update cnc.aidPage set active = 1 where active is null

This should work for you.

油饼 2022-09-12 15:29:34

You can't use '=' to check for NULL. Instead use 'IS NULL':

Update cnc.aidPage 
set active = 1
where active IS NULL 
梦境 2022-09-12 15:29:34

NULL is used as a placeholder for unknown or inapplicable values.

Try:

Update cnc.aidPage set active = 1 where active is null
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文