如果不存在,则使用选择语句插入TSQL

时间:2014-07-15 19:41:46

标签: sql sql-server tsql stored-procedures

我从select语句中将多个记录插入到表中。 select语句可以包含多个记录作为XML字符串。

INSERT INTO empowermentEntries (sessionID, submissionID, whoAdded, [timestamp])
    SELECT @sessionID,
           ParamValues.x1.value('theID[1]', 'INT'),
           @empID,
           GETDATE()
    FROM   @entries.nodes('/submission/submissionID') AS ParamValues(x1);

但是,如果记录已存在,我希望阻止将记录添加到此表中。

是否可以将其与IF NOT EXISTS

结合使用

1 个答案:

答案 0 :(得分:0)

感谢您的信息 - 这有效。

INSERT INTO empowermentEntries (sessionID, submissionID, whoAdded, [timestamp])
    SELECT @sessionID,
           ParamValues.x1.value('theID[1]', 'INT'),
           @empID,
           GETDATE()
    FROM   @entries.nodes('/submission/submissionID') AS ParamValues(x1)
    WHERE not exists(SELECT 
                    sessionID, submissionID
                    FROM empowermentEntries
                    WHERE sessionID = @sessionID AND submissionID = ParamValues.x1.value('theID[1]', 'INT'));