Is it possible in a stored procedure for SQL Server 2008 R2 to have a conditional NOT IN
clause for a SELECT
statement's WHERE
? I have three tables, Employee
, TestingA
, and TestingB
, where employeeID
is a foreign key in TestingA
and TestingB
:
CREATE TABLE [dbo].[Employee](
[employeeID] [int] IDENTITY(9500,1) NOT NULL,
[firstName] [nvarchar](50) NOT NULL,
[middleName] [nvarchar](50) NULL,
[lastName] [nvarchar](50) NOT NULL,
[suffix] [nvarchar](50) NULL,
[createdDate] [datetime] NOT NULL CONSTRAINT [DF_Employee_createdDate] DEFAULT (getdate()),
CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED
(
[employeeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[TestingA](
[testingA_ID] [int] IDENTITY(1,1) NOT NULL,
[employeeID] [int] NOT NULL,
[isComplete] [bit] NULL CONSTRAINT [DF_TestingA_isComplete] DEFAULT ((0)),
[createdDate] [datetime] NOT NULL CONSTRAINT [DF_TestingA_createdDate] DEFAULT (getdate()),
CONSTRAINT [PK_TestingA] PRIMARY KEY CLUSTERED
(
[testingA_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]
CREATE TABLE [dbo].[TestingB](
[testingB_ID] [int] IDENTITY(1,1) NOT NULL,
[employeeID] [int] NOT NULL,
[isComplete] [bit] NULL CONSTRAINT [DF_TestingB_isComplete] DEFAULT ((0)),
[createdDate] [datetime] NOT NULL CONSTRAINT [DF_TestingB_createdDate] DEFAULT (getdate()),
CONSTRAINT [PK_TestingB] PRIMARY KEY CLUSTERED
(
[testingB_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]
I need to do SELECT
on the Employee
table with a conditional NOT IN
for its WHERE
clause based on an input parameter for the stored procedure:
@Type nvarchar(50)
Based on the value of @Type
, I want to do a NOT IN
on TestingA
or TestingB
. So it's something like this:
select e.employeeId from Employee e
where
-- If @Type = 'TestingA' Then
-- e.employeeID NOT IN (select ta.employeeID from TestingA ta)
-- End
-- Else
-- e.employeeID NOT IN (select tb.employeeID from TestingB ta)
-- End
How would I do this in Transact-SQL? Thanks.