我在尝试创建存储过程时遇到了一些问题。我使用Microsoft SQL Server Management Studio 2017和T-SQL。我有2个表,eTasks
和eStaff
。以下是每个表的列:
eStaff
StaffID | Name
eTasks
TaskID | StaffID | Title | CreateDate
目前,正如数据所示,所有任务都分配给StaffID' 1。 eTasks和eStaff表都使用新任务和工作人员更新,或者它们被取出,这些表每天都不会有相同的行。有时候,eTask表中会有1000行,下一行可能只有400行。有时候,eStaff表中会有3名工作人员,其次可能会有12名。
我想要做的是在运行存储过程时在当前StaffID之间均匀分配任务。
到目前为止,这就是我所拥有的:
CREATE PROCEDURE UpdatingeTasksTable
AS
DECLARE t_rowCount INTEGER
DECLARE s_staffIDCount INTEGER
SET t_rowCount = SELECT COUNT(*) FROM eTasks
SET s_staffIDCount = SELECT DISTINCT StaffID FROM eStaff
UPDATE eTasks
SET StaffID = CASE WHEN TaskID % t_rowCount = 1
THEN 1
WHEN TaskID % t_rowCount = 2
THEN 4
WHEN TaskID % t_rowCount = 3
THEN 3
WHEN TaskID % t_rowCount = 4
THEN 2
END
FROM eTasks b
WHERE TaskID = b.TaskID;
我知道,我的查询目前是什么,它只会将任务分成4个人。有没有办法让CASE
语句动态化,这样就不会有一组静态数字?
答案 0 :(得分:0)
您应该可以使用row_number()
:
with s as (
select s.*, row_number() over (order by (select null)) as seqnum,
count(*) over () as cnt
from estaff
),
t as (
select t.*, row_number() over (order by (select null)) as seqnum
from etasks
)
update t
set staffid = s.staffid
from t join
s
on s.seqnum = (t.seqnum % s.cnt) + 1;
答案 1 :(得分:0)
我们可以将NTILE
用于动态人数,例如:
ALTER PROCEDURE UpdatingeTasksTable
AS
BEGIN
DECLARE @t_rowCount INT;
select @t_rowCount = COUNT(*) from eStaff;
WITH CTE AS(
select TaskID,
NTILE(@t_rowCount) OVER (ORDER BY TaskID) AS NTILE,
StaffID, Title,
CreateDate
FROM eTasks)
UPDATE CTE
SET CTE.StaffID=CTE.NTILE
END
执行SP
EXEC UpdatingeTasksTable
检查结果
select * from eTasks