我在这里有一个问题:
alter proc spbadge
@WeekNumber nvarchar(255)
as
begin
update pointsbadge
set
badge1 =(case when WeeklyHoursLogged >= '40' then 1 else 0 end),
badge2 = (case when WeeklyHoursLogged<'40' then 1 else 0 end),
badge3 = (case WHEN WeeklyHoursLogged >= 50 and WeeklyHoursLogged < 55 THEN '1' else 0 end),
badge4 = (case WHEN WeeklyHoursLogged >= 55 and WeeklyHoursLogged < 60 THEN '1' else 0 end),
badge5 = (case WHEN WeeklyHoursLogged >= 60 THEN '1' else 0 end);
end
&#13;
现在,在使用条件运行上述查询后,我已经更新了&#34; pointsBadge&#34;表 -
情景: 在这里你会看到5个徽章(badge1到badge5)。当任何员工获得奖励时,它将变为1,否则为0.例如:Brinda赢得所有徽章,而lyka仅赢得badge1。
问题:我想要另一张桌子&#34; employee_badge&#34; - 每当任何员工获得徽章奖励时,即每当她的价值为1时,在这个&#34; employee_badge&#34; table,employeeid,badgeid和时间被记录下来。
你们怎么认为这可以实现。我修改了上面的存储过程,或者你建议一个更有效的解决方案。我相信我需要在这里使用更新触发器。但是,我将如何在它上面使用它以上存储过程。
答案 0 :(得分:1)
请查看以下代码,如果它符合您的要求:您可以根据您的表格结构和数据调整查询
- 徽章点信息
CREATE TABLE pointsBadge(EmployeeName VARCHAR(50), EmployeeID INT, badge1 INT, badge2 INT, badge3 INT, badge4 INT, badge5 INT)
INSERT INTO pointsBadge VALUES
('Lyka', 1122, 1, 1, 0, 0, 0),
('Brinda', 2233, 0, 0, 0, 0, 0),
('Anil', 34, 1, 1, 0, 0, 1)
- 用于存储徽章数据员工的新表格及当前时间戳
CREATE TABLE employee_badge(id INT IDENTITY(1,1), employee_id INT, badge_id INT, earned_on DATETIME)
- 徽章信息表
CREATE TABLE #badges(BadgeId INT IDENTITY(1, 1), BadgeName VARCHAR(50))
INSERT INTO #badges VALUES
('Badge1'),
('Badge2'),
('Badge3'),
('Badge4'),
('Badge5'),
('Badge6')
- 触发将数据插入带有更新数据的employee_badge表
IF OBJECT_ID('[dbo].[TRGUpdate_badge_info]', 'TR') IS NOT NULL
DROP TRIGGER dbo.TRGUpdate_badge_info
GO
CREATE TRIGGER dbo.TRGUpdate_badge_info ON dbo.pointsBadge
FOR UPDATE
AS
INSERT INTO employee_badge
SELECT d.EmployeeID,
b.BadgeId,
GETDATE()
FROM pointsBadge p
INNER JOIN DELETED d ON p.EmployeeID = d.EmployeeID
INNER JOIN #badges b ON b.BadgeName = CASE WHEN (p.badge1 <> d.badge1) THEN 'Badge1'
WHEN (p.badge2 <> d.badge2) THEN 'Badge2'
WHEN (p.badge3 <> d.badge3) THEN 'Badge3'
WHEN (p.badge4 <> d.badge4) THEN 'Badge4'
WHEN (p.badge5 <> d.badge5) THEN 'Badge5'
END
GO
UPDATE pointsBadge SET badge5 = 2 WHERE employeeID = 1122
SELECT * FROM employee_badge