美好的一天,
我有以下游标查询,并希望将其替换为基于集合的查询以解决性能问题。
DECLARE @EmpIDM CHAR(21);
DECLARE @EmpName CHAR(21);
DECLARE @EMPCatID INT;
DECLARE Assign_Emp SCROLL CURSOR
FOR
SELECT DISTINCT EMP
, EMPNAME
FROM HR_EMPLOYEES
SET NOCOUNT ON
OPEN Assign_Emp;
FETCH NEXT
FROM Assign_Emp
INTO @EmpIDM
, @EmpName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @EMPCatID = (
SELECT TOP 1 CategoryID
FROM Categories
)
UPDATE Categories
SET CategoryID = (CategoryID + 1) /*Increment Category ID for next Insert*/
INSERT INTO Table1 (
EmpNumber
, EmployeeName
, EmployeeCategoryID
)
VALUES (
@EmpIDM
, @EmpName
, @EMPCatID
)
FETCH NEXT
FROM Assign_Emp
INTO @EmpIDM
, @EmpName
END
CLOSE Assign_Emp;
CLOSE Assign_Emp;
SET NOCOUNT OFF
我的挑战是将以下代码段调整为基于集合的操作
SET @EMPCatID = (
SELECT TOP 1 CategoryID
FROM Categories
)
UPDATE Categories
SET CategoryID = (CategoryID + 1) /*Increment Category ID for next Insert*/
我谦虚地欣赏有关如何实现这一目标的任何见解。
非常感谢,
答案 0 :(得分:-1)
使用temp重写。带有标识列的表:
declare @offset int
select @offset = isnull(max(CategoryID),0) from Categories
create table #data (
EmpNumber CHAR(21),
EmployeeName CHAR(21),
EmployeeCategoryID int identity
)
INSERT INTO #data (
EmpNumber
, EmployeeName)
SELECT DISTINCT EmpIDM
, EmpName
FROM HR_EMPLOYEES
insert into Table1 (
EmpNumber
, EmployeeName
, EmployeeCategoryID
) select
EmpNumber
, EmployeeName
, EmployeeCategoryID + @offset
from #data
update Categories
set CategoryID = (select max(EmployeeCategoryID) from #data) + @offset