I've table and data as script below,
CREATE TABLE [dbo].[ClientProjects](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ClientId] [int] NOT NULL,
[ProjectId] [int] NOT NULL,
CONSTRAINT [PK_ClientProjects] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Project] Script Date: 22/10/2021 7:41:27 AM ******/SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Project](
[ProjectId] [int] IDENTITY(1,1) NOT NULL,
[ProjectName] [nvarchar](450) NULL,
CONSTRAINT [PK_Project_1] PRIMARY KEY CLUSTERED
(
[ProjectId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[ClientProjects] ON
GO
INSERT [dbo].[ClientProjects] ([Id], [ClientId], [ProjectId]) VALUES (1, 4, 1)
GO
SET IDENTITY_INSERT [dbo].[ClientProjects] OFF
GO
SET IDENTITY_INSERT [dbo].[Project] ON
GO
INSERT [dbo].[Project] ([ProjectId], [ProjectName]) VALUES (1, N'maybank4u')
GO
INSERT [dbo].[Project] ([ProjectId], [ProjectName]) VALUES (2, N'Salahudin')
GO
INSERT [dbo].[Project] ([ProjectId], [ProjectName]) VALUES (3, N'test')
GO
INSERT [dbo].[Project] ([ProjectId], [ProjectName]) VALUES (4, N'maybank')
GO
SET IDENTITY_INSERT [dbo].[Project] OFF
GO
Table: Project
Table: ClientProjects
How T-SQL looks like to getting result as following,
ProjectId | ProjectName | Selected
---------------------------------------------
1 maybank4u true
2 Salahudin false
3 test false
4 maybank false
All Project must be returned
Read up on OUTER joins. This will do it for you.
https://docs.microsoft.com/en-us/sql/relational-databases/performance/joins?view=sql-server-ver15
SELECT p.ProjectId
,p.ProjectName
,Selected = IIF(cp.ProjectID>0,'true','false')
FROM dbo.Project p
LEFT JOIN dbo.ClientProjects cp
ON p.ProjectId = cp.ProjectId
ORDER BY p.ProjectId
;
--Jeff Moden
Change is inevitable... Change for the better is not.
October 22, 2021 at 6:57 am
Thanks
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply