In der folgenden Funktion habe ich eine Variable - @day_code
innerhalb eines Cursors verwendet und es erhalten unterschiedliche Werte während der Ausführung einer While-Schleife.Dynamisch eine Variable einem Cursor zuweisen - SQL Server
DECLARE @curr_date DATE = GETDATE()
DECLARE @curr_day VARCHAR(10)
DECLARE @day_code VARCHAR(1)
DECLARE @cnt INT = 0
DECLARE @exist INT = 0
DECLARE test_cur CURSOR FOR
SELECT 1
FROM work_cal_time wct
WHERE wct.day_code = @day_code
WHILE @cnt < 3
BEGIN
SET @curr_date = DATEADD(day, -1, @curr_date)
SET @curr_day = DATENAME(weekday, @curr_date)
SET @day_code =
CASE @curr_day
WHEN 'Sunday' THEN '1'
WHEN 'Monday' THEN '2'
WHEN 'Tuesday' THEN '3'
WHEN 'Wednesday' THEN '4'
WHEN 'Thursday' THEN '5'
WHEN 'Friday' THEN '6'
WHEN 'Saturday' THEN '7'
END
OPEN test_cur
FETCH test_cur INTO @exist
CLOSE test_cur
IF @exist = 0 CONTINUE
SET @exist = 0
SET @cnt = @cnt + 1;
END;
RETURN(@curr_date)
END
Aber, so scheint es, wird der Wert der Variablen @day_code
wird nicht durch den Cursor abgeholt. Wenn ich jedoch @day_code
initialisiere, anstatt einen Wert dynamisch zuzuweisen, funktioniert es einwandfrei. heißt
CREATE FUNCTION [dbo].[test]()
RETURNS DATE
AS
BEGIN
DECLARE @curr_date DATE = GETDATE()
DECLARE @curr_day VARCHAR(10)
DECLARE @day_code VARCHAR(1) = '1'
DECLARE @cnt INT = 0
DECLARE @exist INT = 0
DECLARE test_cur CURSOR FOR
SELECT 1
FROM work_cal_time wct
WHERE wct.day_code = @day_code
WHILE @cnt < 3
BEGIN
SET @curr_date = DATEADD(day, -1, @curr_date)
SET @curr_day = DATENAME(weekday, @curr_date)
OPEN test_cur
FETCH test_cur INTO @exist
CLOSE test_cur
IF @exist = 0 CONTINUE
SET @exist = 0
SET @cnt = @cnt + 1;
END;
RETURN(@curr_date)
END
Wie ordne ich dynamisch eine Variable auf einen Cursor?
Bitte nehmen Sie sich einen Blick auf [DATEPART (DW,)] (https://msdn.microsoft.com/en-us/library/ms174420. aspx) –
McNets
Funktionen wie diese sind sehr ineffizient, besonders wenn Sie einen Cursor innerhalb verwenden. Dies könnte leicht als Nicht-Cursor-Version umgeschrieben werden. – DavidG
Es funktioniert gut. Wenn ich debugge, obwohl "@day_code" den richtigen Wert hat, wird es nicht in den Cursor übergeben –