更改where语句以排除重复项

时间:2016-08-22 23:22:54

标签: sql-server sql-server-2008-r2

我有一个存储过程,用于将订单导入调查软件的数据库。目前,它导入了前一天的所有订单,但最近业务计划的变更要求每小时发送一次这些调查。导入来自不同数据库中的视图。属性1是订单号,每次调查都是唯一的,因此我们可以使用它来限制导入。

如何将其更改为不重复?

BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

Insert INTO SurveyTable
(SurveyTable.firstname,
SurveyTable.token,
SurveyTable.email,
SurveyTable.emailstatus, 
SurveyTable.language, 
SurveyTable.remindersent, 
SurveyTable.attribute_1,
SurveyTable.attribute_2)


select 
    location,
    cast( '' as xml ).value('xs:base64Binary(sql:column( "token" ) )', 'nvarchar(MAX)' ),
    email,
    emailstatus, 
    [language],
    remindersent,
    attribute_1,
    attribute_2
from 
    (
        select 
            RTRIM([Closed_Orders_For_Survey].[Location]) location,
            crypt_gen_random(12) as token, 
            [Closed_Orders_For_Survey].[Email] email,
            'OK' emailstatus,
            'en' [language], 
            'N' remindersent, 
           [Closed_Orders_For_Survey].[Order Number] attribute_1, 
            CONVERT(VARCHAR(10), [Closed_Orders_For_Survey].[Invoice Date],110) attribute_2 
        from 
            [Closed_Orders_For_Survey]
        where 
            [Closed_Orders_For_Survey].[Order Date] >= dateadd(DAY, -1, Convert(date, GETDATE()))
    ) as x
END

P.S。令牌是用于创建调查URL的生成的唯一字符串。我们决定不使用订单号作为令牌,因为这样做太可预测,并且人们可以更改其网址以填写其他用户调查。

2 个答案:

答案 0 :(得分:1)

这对于非常大的数据集来说并不是最佳选择(您希望确保在attribute_1上拥有良好的索引),但是您可以执行“不存在的数据集”#39;从已经插入的内部查询中过滤掉任何订单的子句:

select 
    location,
    cast( '' as xml ).value('xs:base64Binary(sql:column( "token" ) )', 'nvarchar(MAX)' ),
    email,
    emailstatus, 
    [language],
    remindersent,
    attribute_1,
    attribute_2
from 
    (
        select 
            RTRIM([Closed_Orders_For_Survey].[Location]) location,
            crypt_gen_random(12) as token, 
            [Closed_Orders_For_Survey].[Email] email,
            'OK' emailstatus,
            'en' [language], 
            'N' remindersent, 
           [Closed_Orders_For_Survey].[Order Number] attribute_1, 
            CONVERT(VARCHAR(10), [Closed_Orders_For_Survey].[Invoice Date],110) attribute_2 
        from 
            [Closed_Orders_For_Survey]
        where 
            [Closed_Orders_For_Survey].[Order Date] >= dateadd(DAY, -1, Convert(date, GETDATE()))
    ) as x
where 
    not exists (
        select attribute_1 
            from SurveyTable 
            where 
                attribute_1 = x.attribute_1
        )

答案 1 :(得分:0)

这可能看起来很愚蠢,但如果令牌是主键,那么插入重复令牌​​的尝试将会失败。陷阱你的应用程序中的特定错误(并且强烈忽略它)并且你是金色的。

如果必须是所有一个交易,您可以随时添加"和令牌(不从表中选择令牌)" subselect(可能效率低下,但应该有效)。