I’m using SQL Server 2008.
Let’s say I have two hypothetical tables like below:
CREATE TABLE [Department](
[Id] int IDENTITY(1,1),
[ManagerId] int NULL, -- << Foreign key to the Person table
-- other fields
)
CREATE TABLE [Person](
[Id] int IDENTITY(1,1),
[DepartmentId] int NOT NULL, -- << Foreign key to the Department table
-- other fields
)
Now, I want to return a list of rows from the [Person] table (i.e. list of staff for a given department). Only one (or zero) of these rows will match the [ManagerId] field in the [Department] table. And I want to flag the matched row with a boolean field on the fly… the resultant rowset will resemble the following schema:
[Id] INT,
[IsManager] BIT NOT NULL DEFAULT 0,
-- other fields
The [IsManager] field will be TRUE when [Department].[ManagerId] matches [Person].[Id].
This is fairly trivial to do with two (or more) queries. But how can I achieve this using a single SQL statement?
Add an expression to your
SELECTclause where you compare actual personsIdwithManagerIdfrom persons department