我有一个这样的存储过程:
SET NOCOUNT ON;
BEGIN TRAN;
INSERT INTO [TaskNotification] (TaskId, EmpKey)
SELECT
TaskId, E.EmpKey
FROM
@TaskNotificationTableType TNT
INNER JOIN
Employee E ON E.EmpGuid = TNT.EmpGuid;
COMMIT TRAN
我想知道如何在插入值之前检查列E.EmpKey
的值是否存在
IF (E.EmpKey EXISTS)
// DO NOTHING
ELSE
INSERT INTO [TaskNotification] (TaskId, EmpKey)
SELECT
TaskId, E.EmpKey
FROM
@TaskNotificationTableType TNT
INNER JOIN
Employee E ON E.EmpGuid = TNT.EmpGuid;
如何实现?问候
答案 0 :(得分:1)
如果您的意思是EmpKey
不必在Employee
上为NULL,那么对WHERE
进行过滤就足够了。
INSERT INTO [TaskNotification] (TaskId, EmpKey)
SELECT
TaskId, E.EmpKey
FROM
@TaskNotificationTableType TNT
INNER JOIN
Employee E ON E.EmpGuid = TNT.EmpGuid
WHERE
E.EmpKey IS NOT NULL;
如果您不想在TaskNotification
中插入一条记录(如果已有的话),请使用WHERE NOT EXISTS
。
INSERT INTO [TaskNotification] (TaskId, EmpKey)
SELECT
TaskId, E.EmpKey
FROM
@TaskNotificationTableType TNT
INNER JOIN
Employee E ON E.EmpGuid = TNT.EmpGuid
WHERE
NOT EXISTS (SELECT 'not in TaskNotification yet' FROM [TaskNotification] T
WHERE T.EmpKey = E.EmpKey)
答案 1 :(得分:0)
@@rowcount
返回受最后一条语句影响的行数。
SET NOCOUNT ON;
BEGIN TRAN;
SELECT E.EmpKey
FROM @TaskNotificationTableType TNT;
IF @@rowcount > 0
INSERT INTO [TaskNotification] (TaskId, EmpKey)
SELECT
TaskId, E.EmpKey
FROM
@TaskNotificationTableType TNT
INNER JOIN
Employee E ON E.EmpGuid = TNT.EmpGuid;
commit tran