如何更改SQL Server选择查询中的布尔值?

时间:2021-10-17 23:58:25

Basically I want to alter the boolean value selecting from the table:

基本上我想改变从表中选择的布尔值:

e.g.:

SELECT otherColumns, not ysnPending FROM table

I need a column ysnPending = true if the value is false & false if the value is true.

如果值为false,我需要一列ysnPending = true,如果值为true,我需要false。

Is there any function available to alter the Boolean value or I should use IIf or CASE...?

有没有可用于改变布尔值的函数,或者我应该使用IIf或CASE ......?

2 个解决方案

#1


3  

use CASE, or if the bit field is non-nullable you could just subtract from 1.

使用CASE,或者如果位字段不可为空,则可以从1减去。

SELECT 
    otherColumns, 
    (1 - ysnPending) -- NOT ysnPending
FROM table 

(Using CASE might lead to more understandable code.)

(使用CASE可能会导致更易理解的代码。)

If ysnPending is nullable, what behaviour do you assign to NOT?

如果ysnPending可以为空,那么你分配给NOT的行为是什么?

#2


0  

Example using a case statement :

使用case语句的示例:

create table table1 (id int not null, ysnPending bit null)
insert table1 values (1, 1)
insert table1 values (2, null)
insert table1 values (3, 0)

select id, cast((case when ysnPending = 1 then 0 else 1 end) as bit) as Not_ysnPending from table1

Assumes you want 1 returned when ysnPending is NULL.

假设当ysnPending为NULL时,您希望返回1。

The cast to bit type is to make sure that the returned column is of a BIT datatype. If you leave it out, it will return an INTEGER type. (This may or may not matter to you, depending on how exactly you are going to use the returned result set).

转换为位类型是为了确保返回的列是BIT数据类型。如果将其遗漏,它将返回INTEGER类型。 (这可能与您有关,也可能无关紧要,具体取决于您将如何使用返回的结果集)。

#1


3  

use CASE, or if the bit field is non-nullable you could just subtract from 1.

使用CASE,或者如果位字段不可为空,则可以从1减去。

SELECT 
    otherColumns, 
    (1 - ysnPending) -- NOT ysnPending
FROM table 

(Using CASE might lead to more understandable code.)

(使用CASE可能会导致更易理解的代码。)

If ysnPending is nullable, what behaviour do you assign to NOT?

如果ysnPending可以为空,那么你分配给NOT的行为是什么?

#2


0  

Example using a case statement :

使用case语句的示例:

create table table1 (id int not null, ysnPending bit null)
insert table1 values (1, 1)
insert table1 values (2, null)
insert table1 values (3, 0)

select id, cast((case when ysnPending = 1 then 0 else 1 end) as bit) as Not_ysnPending from table1

Assumes you want 1 returned when ysnPending is NULL.

假设当ysnPending为NULL时,您希望返回1。

The cast to bit type is to make sure that the returned column is of a BIT datatype. If you leave it out, it will return an INTEGER type. (This may or may not matter to you, depending on how exactly you are going to use the returned result set).

转换为位类型是为了确保返回的列是BIT数据类型。如果将其遗漏,它将返回INTEGER类型。 (这可能与您有关,也可能无关紧要,具体取决于您将如何使用返回的结果集)。