我希望复制表中的一组行,但在 SQL Server 17 中处理唯一列。该表是:
CREATE TABLE test1 (
id int CONSTRAINT PK_test1 PRIMARY KEY CLUSTERED IDENTITY,
name nvarchar(10) CONSTRAINT UK_test1 UNIQUE NONCLUSTERED,
value int,
type varchar(20)
);
表格内容为:
INSERT INTO test1 VALUES ('e_1',1,'A');
INSERT INTO test1 VALUES ('342A',34,'ABC');
INSERT INTO test1 VALUES ('Tame_33',277,'Test10');
现在我希望多次复制这些行,但问题在于 NAME 列是唯一的。到目前为止我所做的解决方案只是使用光标,但这效率低下,我很好奇这是否可以以更有效的方式完成?
DECLARE @id int;
DECLARE @name nvarchar(20);
DECLARE @value int;
DECLARE @type varchar(10);
DECLARE @cnt int = 0;stackoverflow
DECLARE @intcnt int = 0;
DECLARE temp_cursor CURSOR FOR
SELECT * FROM test1
OPEN temp_cursor;
FETCH NEXT FROM temp_cursor INTO @id,@name,@value,@type;
WHILE @@FETCH_STATUS = 0
BEGIN
WHILE @intcnt < 5
BEGIN
INSERT INTO test1 VALUES
('ins_' + CONVERT(varchar,@intcnt) + '_' + CONVERT(varchar,@cnt), @value, @type);
SET @intcnt = @intcnt + 1;
END
SET @intcnt = 0;
FETCH NEXT FROM temp_cursor INTO @id,@name,@value,@type;
SET @cnt = @cnt + 1;
END
CLOSE temp_cursor;
DEALLOCATE temp_cursor;