열의 내용에 따라 T-SQL에서 부울을 출력하는 방법은 무엇입니까?
-
03-07-2019 - |
문제
나는 다른 테이블과 사전 필터 및 사전에 다른 테이블의 추상 열을 보았습니다. 컨텐츠가 신경 쓰지 않는 열이 하나 있지만 내용이 무효인지 아닌지 알아야합니다. 그래서 내 견해는 "진실"이 지정된 열의 값을 경우에 NULL이 아닙니다 그리고 "거짓"값의 경우 NULL입니다.
T-SQL로 이러한 부울을 선택하려면 어떻게해야합니까?
해결책
You have to use a CASE statement for this:
SELECT CASE WHEN columnName IS NULL THEN 'false' ELSE 'true' END FROM tableName;
다른 팁
Or you can do like this:
SELECT RealColumn, CAST(0 AS bit) AS FakeBitColumn FROM tblTable
If you need a output as boolean
CAST(CASE WHEN colName IS NULL THEN 0 ELSE 1 END as BIT) aIsBooked
for the column in the view you can use something like
CASE WHEN ColumnName is not null THEN 'True' ELSE 'False' END
or in a statement
SELECT
s.ID,
s.[Name],
CASE WHEN s.AchievedDate is not null THEN 'True' ELSE 'False' END [IsAchieved]
FROM Schools s
or for further processing afterwards I would personally use
SELECT
s.ID,
s.[Name],
CASE WHEN s.AchievedDate is not null THEN 1 ELSE 0 END [IsAchieved]
FROM Schools s
I had a similar issue where I wanted a view to return a boolean column type based on if an actual column as null or not. I created a user defined function like so:
CREATE FUNCTION IsDatePopulated(@DateColumn as datetime)
RETURNS bit
AS
BEGIN
DECLARE @ReturnBit bit;
SELECT @ReturnBit =
CASE WHEN @DateColumn IS NULL
THEN 0
ELSE 1
END
RETURN @ReturnBit
END
Then the view that I created returns a bit column, instead of an integer.
CREATE VIEW testView
AS
SELECT dbo.IsDatePopulated(DateDeleted) as [IsDeleted]
FROM Company
You asked for boolean, which we call bit in t-sql.
Other answers have either given you a varchar 'true' and 'false' or 1 and 0. 'true' and 'false' are obviously varchar, not boolean. I believe 1 and 0 would be cast as an integer, but it's certainly not a bit. This may seem nit-picky, but types matter quite often.
To get an actual bit value, you need to cast your output explicitly as a bit like:
select case when tableName.columnName IS NULL then cast(0 as bit) else cast(1
as bit) END as ColumnLabel from tableName