Development Tip

SQL Server-부울 리터럴?

yourdevel 2020. 11. 3. 19:20
반응형

SQL Server-부울 리터럴?


SQL Server에서 리터럴 부울 값을 작성하는 방법은 무엇입니까? 샘플 사용보기 :

select * from SomeTable where PSEUDO_TRUE

다른 샘플 :

if PSEUDO_TRUE
begin
  select 'Hello, SQL!'
end 

참고 : 위의 쿼리는 사용 방법과 관련이 없습니다. 리터럴 부울을 테스트하는 것입니다.


SQL Server에는 부울 데이터 유형 이 없습니다 . @Mikael이 지적했듯이 가장 가까운 근사치는 비트입니다. 그러나 그것은 부울 유형이 아니라 숫자 유형입니다. - 또한, 2 개 값은 지원 0또는 1(및 하나의 비 값 NULL).

SQL (표준 SQL 및 T-SQL 언어)은 세 가지 가치 논리를 설명합니다 . SQL에 대한 부울 유형은 3 개의 값 ( TRUE, FALSE비값)을 지원해야합니다 . 그래서 실제로 여기에 좋은 일치가 아닙니다.UNKNOWNNULLbit

SQL Server가 데이터 유형을 지원하지 않는다는 점을 감안할 때 해당 "유형"의 리터럴을 쓸 수있을 것으로 기 대해서는 안됩니다.


select * from SomeTable where 1=1

이것은 다른 답변에서 언급되지 않았습니다. 부울로 수화 해야하는 값을 원한다면 다음을 사용할 수 있습니다.

CONVERT (비트, 0)-거짓 CONVERT (비트, 1)-참

이것은 부울이 아닌 비트를 제공합니다. 예를 들어 if 문에서는 해당 값을 사용할 수 없습니다.

IF CONVERT(bit, 0)
BEGIN
    print 'Yay'
END

구문 분석하지 않습니다. 당신은 여전히 ​​쓸 필요가 있습니다

IF CONVERT(bit, 0) = 0

그래서 그다지 유용하지 않습니다.


Microsoft 에 따르면 검색 구문은

[ WHERE <search_condition> ]*

검색 조건은 다음과 같습니다.

<search_condition> ::= 
    { [ NOT ] <predicate> | ( <search_condition> ) } 
    [ { AND | OR } [ NOT ] { <predicate> | ( <search_condition> ) } ] 
[ ,...n ] 

그리고 술어는 다음과 같습니다.

<predicate> ::= 
    { expression { = | < > | ! = | > | > = | ! > | < | < = | ! < } expression 

보시다시피, 항상 비교할 두 개의 표현식을 작성해야합니다. 여기서 검색 조건은 1 = 1, a! = b와 같은 부울 표현식입니다 .

검색 표현식을 'True' 또는 'False' 와 같은 부울 상수혼동하지 마십시오 . BIT 변수에 부울 상수를 할당 할 수 있습니다.

DECLARE @B BIT
SET @B='True'

그러나 TSQL에서는 다음과 같은 부울 식 대신 부울 상수를 사용할 수 없습니다.

SELECT * FROM Somewhere WHERE 'True'

이거 작동 안 할거야.

그러나 부울 상수를 사용하여 다음과 같은 양면 검색 표현식을 작성할 수 있습니다.

SEARCH * FROM Somewhere WHERE 'True'='True' 

대부분의 데이터베이스는 다음을 허용합니다.

select * from SomeTable where true

그러나 일부 데이터베이스 (예 : SQL Server, Oracle)에는 부울 유형이 없습니다. 이러한 경우 다음을 사용할 수 있습니다.

select * from SomeTable where 1=1

BTW, sql where 절을 직접 빌드하는 경우 where 절에 추가하려는 조건이 첫 번째 조건인지 알 필요가 없기 때문에 이것은 코드를 단순화하는 기초 가됩니다. "WHERE") 또는 후속 항목 (앞에 와야 함 "AND"). 항상로 시작 "WHERE 1=1"하면 where 절에 추가 된 모든 조건 (있는 경우)이 앞에옵니다 "AND".


SQL Server에는 리터럴 true 또는 false 값이 없습니다. 1=1드문 경우에이 방법 (또는 유사한 방법) 을 사용해야 합니다.

한 가지 옵션은 true 및 false에 대해 고유 한 명명 된 변수를 만드는 것입니다.

DECLARE @TRUE bit
DECLARE @FALSE bit
SET @TRUE = 1
SET @FALSE = 0

select * from SomeTable where @TRUE = @TRUE

그러나 이들은 배치 범위 내에서만 존재합니다 (사용하려는 모든 배치에서 다시 선언해야 함).


How to write literal boolean value in SQL Server?
select * from SomeTable where PSEUDO_TRUE

There is no such thing.

You have to compare the value with something using = < > like .... The closest you get a boolean value in SQL Server is the bit. And that is an integer that can have the values null, 0 and 1.


You can use the values 'TRUE' and 'FALSE'. From https://docs.microsoft.com/en-us/sql/t-sql/data-types/bit-transact-sql:

The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.


You should consider that a "true value" is everything except 0 and not only 1. So instead of 1=1 you should write 1<>0.

Because when you will use parameter (@param <> 0) you could have some conversion issue.

The most know is Access which translate True value on control as -1 instead of 1.


I question the value of using a Boolean in TSQL. Every time I've started wishing for Booleans & For loops I realised I was approaching the problem like a C programmer & not a SQL programmer. The problem became trivial when I switched gears.

In SQL you are manipulating SETs of data. "WHERE BOOLEAN" is ineffective, as does not change the set you are working with. You need to compare each row with something for the filter clause to be effective. The Table/Resultset is an iEnumerable, the SELECT statement is a FOREACH loop.

Yes, "WHERE IsAdmin = True" is nicer to read than "WHERE IsAdmin = 1"

Yes, "WHERE True" would be nicer than "WHERE 1=1, ..." when dynamically generating TSQL.

and maybe, passing a Boolean to a stored proc may make an if statement more readable.

But mostly, the more IF's, WHILE's & Temp Tables you have in your TSQL, the more likely you should refactor it.


I hope this answers the intent of the question. Although there are no Booleans in SQL Server, if you have a database that had Boolean types that was translated from Access, the phrase which works in Access was "...WHERE Foo" (Foo is the Boolean column name). It can be replaced by "...WHERE Foo<>0" ... and this works. Good luck!


select * from SomeTable where null is null

or

select * from SomeTable where null is not null

maybe this is the best performance?

참고URL : https://stackoverflow.com/questions/7170688/sql-server-boolean-literal

반응형

'Development Tip' 카테고리의 다른 글

Android 레이아웃 오른쪽 정렬  (0) 2020.11.03
자바 "?"  (0) 2020.11.03
Java 8의 기본 Xmxsize  (0) 2020.11.03
Xcode 스토리 보드 : 내부 오류.  (0) 2020.11.03
2D 벡터의 외적 계산  (0) 2020.11.03