1

我有一条 SQL 语句要修改。就目前而言,我正在运行一个简单的 SELECT INTO 但我想对其进行修改,以便仅附加目标表中不存在的记录(由我的标准确定)。

这是我最初的声明:

SELECT b.BallotID, m.MeetingDate
    INTO StagingTable
    FROM Ballot INNER JOIN Meeting on b.MeetingID = m.MeetingID
    WHERE b.LastModifiedDate < '01-01-2010' AND ( b.BallotType = 'Agenda Vote' AND m.MeetingDate < GETDATE())  

我想更改一些内容,以便仅在选票尚不存在时填充 StagingTable。这是一种可以接受的方式,还是有更好的选择?

SELECT b.BallotID, m.MeetingDate
    INTO StagingTable
    FROM Ballot INNER JOIN Meeting on b.MeetingID = m.MeetingID
    WHERE b.LastModifiedDate < '01-01-2010' AND ( b.BallotType = 'Agenda Vote' AND m.MeetingDate < GETDATE())   
    AND NOT EXISTS(SELECT 1 from StagingTable where BallotID = b.BallotID)) )
4

2 回答 2

2

您的技术看起来不错,除了SELECT...INTO语法用于创建一个全新的表。相反,您希望使用下面的代码将行添加到现有表中:

INSERT INTO StagingTable
    (BallotID, MeetingDate)
    SELECT b.BallotID, m.MeetingDate
        FROM Ballot b
            INNER JOIN Meeting m
                on b.MeetingID = m.MeetingID
        WHERE b.LastModifiedDate < '01-01-2010' 
            AND (b.BallotType = 'Agenda Vote' AND m.MeetingDate < GETDATE())   
            AND NOT EXISTS(SELECT 1 from StagingTable where BallotID = b.BallotID)
于 2010-10-13T20:28:38.890 回答
1

SELECT INTO创建一个新表,而不是将数据插入到现有表中。因此,我会检查表是否存在,然后在运行现有 SQL 之前删除该表。这将确保每次都删除并重新创建 StagingTable。

    IF OBJECT_ID('StagingTable','U') IS NOT NULL
    BEGIN
         DROP TABLE StagingTable
    END


        SELECT b.BallotID, m.MeetingDate
        INTO StagingTable
        FROM Ballot INNER JOIN Meeting on b.MeetingID = m.MeetingID
        WHERE b.LastModifiedDate < '01-01-2010' AND ( b.BallotType = 'Agenda Vote' 
        AND m.MeetingDate < GETDATE()) 

如果您想向现有表添加行,那么您应该INSERT INTO按照 Joe Stefanelli 的回答使用。

于 2010-10-13T20:30:47.560 回答