我在 SQL Server DB 中有一个表“对象”。它包含对象的名称(字符串)。我有一个新对象的名称列表,需要在单独的表“NewObjects”中插入“对象”表中。此后,此操作将称为“导入”。
如果记录名称已经存在于“对象”中,我需要为要从“NewObjects”导入到“对象”的每条记录生成一个唯一名称。这个新名称将针对旧名称存储在“NewObjects”表中。
DECLARE @NewObjects TABLE
(
...
Name varchar(20),
newName nvarchar(20)
)
我已经实现了一个存储过程,它为要从“NewObjects”导入的每条记录生成唯一的名称。但是,我对 1000 条记录(在“NewObjects”中)的性能不满意。我需要帮助来优化我的代码。下面是实现:
PROCEDURE [dbo].[importWithNewNames] @args varchar(MAX)
-- Sample of @args is like 'A,B,C,D' (a CSV string)
...
DECLARE @NewObjects TABLE
(
_index int identity PRIMARY KEY,
Name varchar(20),
newName nvarchar(20)
)
-- 'SplitString' function: this is a working implementation which is right now not concern of performance
INSERT INTO @NewObjects (Name)
SELECT * from SplitString(@args, ',')
declare @beg int = 1
declare @end int
DECLARE @oldName varchar(10)
-- get the count of the rows
select @end = MAX(_index) from @NewObjects
while @beg <= @end
BEGIN
select @oldName = Name from @NewObjects where @beg = _index
Declare @nameExists int = 0
-- this is our constant. We cannot change
DECLARE @MAX_NAME_WIDTH int = 5
DECLARE @counter int = 1
DECLARE @newName varchar(10)
DECLARE @z varchar(10)
select @nameExists = count(name) from Objects where name = @oldName
...
IF @nameExists > 0
BEGIN
-- create name based on pattern 'Fxxxxx'. Example: 'F00001', 'F00002'.
select @newName = 'F' + REPLACE(STR(@counter, @MAX_NAME_WIDTH, 0), ' ', '0')
while EXISTS (select top 1 1 from Objects where name = @newName)
OR EXISTS (select top 1 1 from @NewObjects where newName = @newName)
BEGIN
select @counter = @counter + 1
select @newName = 'F' + REPLACE(STR(@counter, @MAX_NAME_WIDTH, 0), ' ', '0')
END
select top 1 @z = @newName from Objects
update @NewObjects
set newName = @z where @beg = _index
END
select @beg = @beg + 1
END
-- finally, show the new names generated
select * from @NewObjects