从临时表SQL

时间:2016-03-08 11:21:36

标签: sql insert sql-server-2012 add

尝试将tempTable中的行添加到表时遇到问题。问题是它添加了TempDealer表中的行,即使它们已经在经销商表中(请注意我在WHERE语句中指定WHERE td.supplier_ref NOT IN(SELECT supplier_ref FROM @dealerStatus)。每次运行存储过程时,它都会再次添加从TempDealer到Dealership表的所有行,只需添加一次。任何想法?提前感谢。

        INSERT INTO @dealerStatus (dealerId, supplier_ref, [add], [timestamp])
            SELECT NULL, td.supplier_ref, 1, GETDATE()
                FROM TempDealer td 
                WHERE td.supplier_ref NOT IN (SELECT supplier_ref FROM @dealerStatus) 

            INSERT INTO Dealership( 
                    dealership_name, 
                    telephone, 
                    fax, 
                    sales_email, 
                    support_email, 
                    service_mask, 
                    address1, 
                    address2, 
                    town, 
                    county, 
                    postcode, 
                    website, 
                    date_modified, 
                    supplier_ref, 
                    dealer_type, 
                    county_id, 
                    town_id, 
                    area_id, 
                    district_id,
                    longitude,
                    latitude
                    ) 

                SELECT DISTINCT
                        [updateSource].leasing_broker_name, 
                        [updateSource].telephone, 
                        [updateSource].fax_number, 
                        [updateSource].email, 
                        [updateSource].support_email, 
                        [updateSource].service_mask, 
                        [updateSource].address1, 
                        [updateSource].address2, 
                        [updateSource].town, 
                        [updateSource].county, 
                        [updateSource].post_code, 
                        [updateSource].web_address, 
                        GETDATE(), 
                        [updateSource].supplier_ref, 
                        1, 
                        [updateSource].county_id, 
                        [updateSource].town_id, 
                        [updateSource].region, 
                        [updateSource].district, 
                        [updateSource].longitude,
                        [updateSource].latitude
                    FROM 
                        @dealerStatus dealerUpdateStatus INNER JOIN 
                        TempDealer [updateSource] ON dealerUpdateStatus.supplier_ref = updateSource.supplier_ref
                    WHERE 
                        dealerUpdateStatus.[add] = 1    

1 个答案:

答案 0 :(得分:1)

我这样排序:

        INSERT INTO @dealerStatus (dealerId, supplier_ref, [add], [timestamp])
            SELECT NULL, td.supplier_ref, 1, GETDATE()
                FROM TempDealer td 
                WHERE td.supplier_ref NOT IN (SELECT supplier_ref FROM Dealership WHERE dealership.supplier_ref IS NOT NULL and dealership.dealer_type = 1)