Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return true or false from tsql using case when

Tags:

tsql

case-when

I'm trying to return true or false based on a CASE WHEN THEN tsql statement, but the only thing that ever shows up in the results panel is the column name "IsGeneric".

Where am I going wrong?

alter proc Storefront.proc_IsProjectGeneric

@ProjectID INT
AS
SET NOCOUNT ON;

SELECT 'IsGeneric'=CASE WHEN p.[GenericCatalogID] > 0 THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END
                 FROM Storefront.Project p WITH(NOLOCK)
                 WHERE p.ID = @ProjectID;

SET NOCOUNT OFF;
like image 233
Filling The Stack is What I DO Avatar asked Oct 25 '13 19:10

Filling The Stack is What I DO


People also ask

How do you return a Boolean in a CASE statement?

The Case function cannot return a boolean (true/false) but only numbers or text. So if it's used in a formula field that is a Boolean, you have to have a return a result and then set your case function equal to the result that you substituted for true.

How do you get true or false in SQL?

SQL Server does not have the Boolean data type. There are no built-in values true and false . One alternative is to use strings 'true' and 'false' , but these are strings just like any other string. Often the bit type is used instead of Boolean as it can only have values 1 and 0 .

Can we use case and if statement in SQL?

The CASE statement is SQL's way of handling if/then logic. The CASE statement is followed by at least one pair of WHEN and THEN statements—SQL's equivalent of IF/THEN in Excel.

Can you do a case when inside of a case when SQL?

CASE can be nested in another CASE as well as in another IF…ELSE statement. In addition to SELECT, CASE can be used with another SQL clause like UPDATE, ORDER BY.


1 Answers

You are using apostrophes around the identifier, which makes it a string instead.

SELECT IsGeneric = CASE WHEN p.[GenericCatalogID] > 0 THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END
             FROM Storefront.Project p WITH(NOLOCK)
             WHERE p.ID = @ProjectID;
like image 171
Guffa Avatar answered Sep 23 '22 11:09

Guffa