在插入列之前检查列是否包含值T-SQL

时间:2018-07-16 22:19:04

标签: sql-server tsql

我有一个这样的存储过程:

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;

如何实现?问候

2 个答案:

答案 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