SQL Server 2012,我将光标设置为:
DECLARE @EmployeeID nchar(10)
DECLARE @TotalDaysWorked nchar(10)
DECLARE @GetEmmployeeID CURSOR
SET @GetEmmployeeID = CURSOR FOR
SELECT [Emp#]
FROM [dbo].[Transform] where Home='ROOMS'
OPEN @GetEmmployeeID
FETCH NEXT
FROM @GetEmmployeeID INTO @EmployeeID
WHILE @@FETCH_STATUS = 0
BEGIN
光标开始运行内部
SELECT Emp#,
(
(CASE WHEN [WK1_Day1] IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN [WK1_Day2] IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN [WK1_Day3] IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN [WK1_Day4] IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN [WK1_Day5] IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN [WK1_Day6] IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN [WK1_Day7] IS NOT NULL THEN 1 ELSE 0 END)
)
AS total_days_worked
FROM [dbo].[Transform]
WHERE [Emp#]=@EmployeeID and [Home] = 'Rooms'
--This is what I can't figure out how to do... the rest works
--UPDATE
--[dbo].[Transform]
--Set [Week1DaysWorked] = total_days_worked
--Get the next record
FETCH NEXT
FROM @GetEmmployeeID INTO @EmployeeID
END
CLOSE @GetEmmployeeID
DEALLOCATE @GetEmmployeeID
答案 0 :(得分:1)
我认为你不需要cursor
。
您可以改为使用基于集合update
。试试这个。
UPDATE
[dbo].[Transform]
set [Week1DaysWorked] = (CASE WHEN [WK1_Day1] IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN [WK1_Day2] IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN [WK1_Day3] IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN [WK1_Day4] IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN [WK1_Day5] IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN [WK1_Day6] IS NOT NULL THEN 1 ELSE 0 END)
+ (CASE WHEN [WK1_Day7] IS NOT NULL THEN 1 ELSE 0 END)
where [Home] = 'Rooms'