【问题标题】:Make INSERT query go slower or check if value exists使 INSERT 查询变慢或检查值是否存在
【发布时间】:2022-01-11 07:42:45
【问题描述】:

我有一个加密的标量值函数,它基于当前时间为表生成唯一 ID。让我们调用函数 dbo.GenerateRecID

我在 SQL Server 中有一个 INSERT 查询,然后调用此函数来插入表的唯一记录 ID。

将此表命名为 Contacts,其中包含以下列:

RecID varchar(15)
Name varchar(20)
Age varchar(50)

我想像这样从另一个名为 Users 的表中插入 Contacts

INSERT INTO Contacts (RecID,Name,Age) values (SELECT dbo.GenerateRecID(),UserName,UserAge FROM USERS)

问题在于,带有 dbo.GenerateRecID() 函数(这是软件为我们提供的加密函数,因此我无法更改)的 INSERT 太快了。因为它每毫秒被调用多次,所以它生成相同的 ID,所以我在插入时得到了重复的值。

有没有办法为每个插入的行创建一个延迟,以使函数生成多个 ID 并避免这个问题(就像编程中的 for each 和 sleep 一样)?或者作为替代方案,有没有办法使用 try 和 catch 来检查是否插入了重复项并再次调用该函数?

【问题讨论】:

标签: sql sql-server tsql


【解决方案1】:

您可以执行每个用户插入并确保 RecID 不存在于联系人数据库中

declare @newID varchar(15)

while exists(select 1 from USERS where not exists (select 1 from contacts where name = username))  -- get Users which are not in the Contacts table
begin
       select @newID =  dbo.GenerateRecID()  -- gets the new ID
  
       while not exists(select 1 from contacts where RecID = @newID)   -- if newID is not in Contacts then use it otherwise generate a new one
         begin
             insert into Contacts(RecID,Name,Age)   -- Insert users 1 at a time
             select top 1 @newID,UserName,UserAge from USERS
             where not exists (select 1 from contacts where name = username))

         end

end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 2015-10-16
    • 2011-06-10
    • 1970-01-01
    • 2011-05-06
    相关资源
    最近更新 更多