Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Exists question

Status
Not open for further replies.
Nov 18, 2003
5
US
I am making a view and want to make a column that returns a boolean. The column will check for a record in another table, if it exists then true else false.


This is what I have and ofcourse it doesn't work but the linking is correct.

(Select Top 1 LotID From TravelerLot Where LotID = dbo.WorkOrderLot.ID)

All that code does is returns a NULL value if it doesn't exist and the LotID if it does. I'd rather it be a boolean.
 
Try this as a column definition:

SELECT
...Other columns...
, HasTravelerLot = CASE
WHEN (Select Top 1 LotID
From TravelerLot
Where LotID = dbo.WorkOrderLot.ID) IS NOT NULL
THEN 1
ELSE 0 END
FROM ...
WHERE ...

--Angel [rainbow]
-----------------------------------
Every time I lose my mind, I wonder
if it's really worth finding.
 
Another option that is slightly faster is this format. This is because EXISTS causes the actual subquery not to actually produce a result set.

SELECT CASE WHEN EXISTS (SELECT 1 FROM dbo.employee WHERE fname = 'Wayne')
THEN 1
ELSE 0
END
 
My offering

SELECT CASE WHEN count(*) > 0 THEN 1 ELSE 0 END As SomeLots From TravelerLot Where LotID = dbo.WorkOrderLot.ID
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top