I have a query where I send a TableType who have columns EmpKey
and TaskId
like:
@AssignNotificationTableType [dbo].[udf_TaskNotification] READONLY
INSERT INTO [TaskNotification] ([TaskId], [EmpKey])
SELECT
[ANT].[TaskId], [E].[EmpKey]
FROM
@AssignNotificationTableType AS [ANT]
INNER JOIN
[Employee] AS [E] ON [ANT].[EmpGuid] = [E].[EmpGuid]
So my table looks like this:
+--------------------------------------+--------------------------------------+--------+
| TaskNotificationId | TaskId | EmpKey |
+--------------------------------------+--------------------------------------+--------+
| EEE3D3F8-F190-E811-841F-C81F66DACA6A | D0440DEB-404C-4006-870F-E95BFFA840E0 | 44 |
| EFE3D3F8-F190-E811-841F-C81F66DACA6A | D0440DEB-404C-4006-870F-E95BFFA840E0 | 49 |
+--------------------------------------+--------------------------------------+--------+
As you can see two items have same TaskId
but different Empkey
, so suppose if I send again same TaskId
D0440DEB-404C-4006-870F-E95BFFA840E0
I want to insert only row only if EmpKey does not exist in that TaskId
So if I send something like:
+--+--------------------------------------+--------+
| | TaskId | EmpKey |
+--+--------------------------------------+--------+
| | D0440DEB-404C-4006-870F-E95BFFA840E0 | 44 |
| | D0440DEB-404C-4006-870F-E95BFFA840E0 | 49 |
| | D0440DEB-404C-4006-870F-E95BFFA840E0 | 54 |
+--+--------------------------------------+--------+
It will only insert last row, because EmpKey
54 does not exist in that TaskId
I try to do in WHERE
clause with NOT IN
as:
INSERT INTO [TaskNotification] ([TaskId], [EmpKey])
SELECT
[ANT].[TaskId], [E].[EmpKey]
FROM
@AssignNotificationTableType AS [ANT]
INNER JOIN
[Employee] AS [E] ON [ANT].[EmpGuid] = [E].[EmpGuid]
WHERE
[E].[EmpKey] NOT IN (SELECT EmpKey
FROM [TaskNotification]
WHERE TaskId = (SELECT TaskId
FROM @AssignNotificationTableType))
But when I run it, it just don't insert anything. What am I doing wrong? Regards