布尔值“NOT” 在 T-SQL 中,不能在“位”上工作; 数据类型?
尝试执行单个布尔 NOT 操作,似乎在 MS SQL Server 2005 下,以下块不起作用
DECLARE @MyBoolean bit;
SET @MyBoolean = 0;
SET @MyBoolean = NOT @MyBoolean;
SELECT @MyBoolean;
相反,我在使用
DECLARE @MyBoolean bit;
SET @MyBoolean = 0;
SET @MyBoolean = 1 - @MyBoolean;
SELECT @MyBoolean;
Yet,这看起来有点扭曲的方式来表达像否定这样简单的东西。
我错过了什么吗?
Trying to perform a single boolean NOT operation, it appears that under MS SQL Server 2005, the following block does not work
DECLARE @MyBoolean bit;
SET @MyBoolean = 0;
SET @MyBoolean = NOT @MyBoolean;
SELECT @MyBoolean;
Instead, I am getting more successful with
DECLARE @MyBoolean bit;
SET @MyBoolean = 0;
SET @MyBoolean = 1 - @MyBoolean;
SELECT @MyBoolean;
Yet, this looks a bit a twisted way to express something as simple as a negation.
Am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用 ~ 运算符:
Use the ~ operator:
您的解决方案是一个很好的解决方案...您还可以使用此语法在 SQL 中进行一些切换...
Your solution is a good one... you can also use this syntax to toggle a bit in SQL...
从 1 中减去该值看起来可以解决问题,但就表达意图而言,我认为我更愿意选择:
它更冗长,但我认为它更容易理解。
Subtracting the value from 1 looks like it'll do the trick, but in terms of expressing intent I think I'd prefer to go with:
It's more verbose but I think it's a little easier to understand.
要分配反转位,您需要使用按位 NOT 运算符。 使用按位 NOT 运算符“~”时,必须确保将列或变量声明为位。
这不会给你零:
这将:
所以这将是:
To assign an inverted bit, you'll need to use the bitwise NOT operator. When using the bitwise NOT operator, '~', you have to make sure your column or variable is declared as a bit.
This won't give you zero:
This will:
So will this:
在 SQL 2005 中,没有真正的布尔值,位值实际上是其他东西。
一个位可以有三种状态:1、0 和 null(因为它是数据)。 SQL 不会自动将这些转换为 true 或 false(尽管令人困惑的是 SQL 企业管理器会)将
逻辑中的位字段视为 1 或 0 的整数。
如果直接在位字段上使用逻辑,它将行为与任何其他值变量类似 - 即,如果它有一个值(任何值),则逻辑将为 true,否则为 false。
In SQL 2005 there isn't a real boolean value, the bit value is something else really.
A bit can have three states, 1, 0 and null (because it's data). SQL doesn't automatically convert these to true or false (although, confusingly SQL enterprise manager will)
The best way to think of bit fields in logic is as an integer that's 1 or 0.
If you use logic directly on a bit field it will behave like any other value variable - i.e. the logic will be true if it has a value (any value) and false otherwise.
BIT 是数字数据类型,而不是布尔值。 这就是为什么您不能对其应用布尔运算符的原因。
SQL Server 没有 BOOLEAN 数据类型(不确定 SQL SERVER 2008),因此您必须坚持使用 @Matt Hamilton 的解决方案。
BIT is a numeric data type, not boolean. That's why you can't apply boolean operators to it.
SQL Server doesn't have BOOLEAN data type (not sure about SQL SERVER 2008) so you have to stick with something like @Matt Hamilton's solution.
使用
ABS
获取绝对值(-1变成1)...Use
ABS
to get the absolute value (-1 becomes 1)...