Link to home
Start Free TrialLog in
Avatar of Grayson Hampton
Grayson Hampton

asked on

SQL Case Statement used with an Alias

Is there a way to use a Case Statement with an alias.
I would like Case statement to return a 0 or 1 based on preContPaid

SELECT Name
RTRIM([CompanyID) + ' ' + RTRIM([CustomerNumber) + ' ' + RTRIM([JobNumber)  as [preContPaid],
CASE
      WHEN [preContPaid] = NULL
      THEN NULL
      ELSE [preContPaid]

FROM Jobs_Rept
Avatar of slightwv (䄆 Netminder)
slightwv (䄆 Netminder)

You cannot use an alias in the same level it is created.


Nothign can '=' null so you need to use "is null".  

Not sure how your will get a null concatenating a ' ' in the string.

Anyway, either a CTE or sub select.

with CTE as (
	SELECT Name,
		RTRIM([CompanyID) + ' ' + RTRIM([CustomerNumber) + ' ' + RTRIM([JobNumber)  as [preContPaid]
	FROM Jobs_Rept
)
select 
	CASE
      WHEN [preContPaid] is NULL
      THEN 0
      ELSE 1
from CTE

Open in new window

Avatar of Grayson Hampton

ASKER

@slightwv...

I am receiving an "incorrect syntax" error on "from CTE"
Nevermind...I forgot the "End"
@slightwv...

The query is not returning "SELECT Name,"

I want it to also show other fields that are not part of the alias
ASKER CERTIFIED SOLUTION
Avatar of slightwv (䄆 Netminder)
slightwv (䄆 Netminder)

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you for your help.