我有一个 SQL 语句在雪花中运行良好,但是当我将其转换为用户定义函数时,它抛出了意外错误。
这是在雪花中运行良好的 SQL 语句:
Declare originalcontent String default('"ezyVetReminderFuture6weeksPostcard"
<br /> "AnimalNextVaccinationDate_Start"08-31-2026"AnimalNextVaccinationDate_End"
<br /> "AnimalNextVaccinationName_Start"DAP"AnimalNextVaccinationName_End"
<br /> "AnimalLastVisitDate_Start"09-01-2023"AnimalLastVisitDate_End"
<br /> "AnimalNextAppointmentDate_Start""AnimalNextAppointmentDate_End"
<br /> "AnimalSOCDueInNextYear_Start"
<ul><li>Wellness Blood and Urine Screen Due on 03-13-2024</li>
<li>Wellness Exam Due on 05-13-2024</li>
</ul>"AnimalSOCDueInNextYear_End"');
extracttext String;
sol String;
sol_refined String;
content String;
Begin
content := originalcontent;
while (REGEXP_INSTR(content, '<li>')>1) do
extracttext := SUBSTRING(content, REGEXP_INSTR(content, '<li>'), REGEXP_INSTR(content,'</li>')-REGEXP_INSTR(content, '<li>'))||'</li>';
IF (sol IS NULL) THEN
sol := extracttext;
ELSE
sol := sol || extracttext;
END IF;
IF (sol_refined IS NULL) THEN
sol_refined := CASE WHEN
DATEDIFF('month', GETDATE(), TRY_TO_DATE(SUBSTRING(RIGHT(extracttext, 15), 1, 10),'MM-DD-YYYY')) <= 3
THEN extracttext ELSE '' END;
ELSE
sol_refined := sol_refined || CASE WHEN
DATEDIFF('month', GETDATE(), TRY_TO_DATE(SUBSTRING(RIGHT(extracttext, 15), 1, 10),'MM-DD-YYYY')) <= 3
THEN extracttext ELSE '' END;
END IF;
content := replace(content,extracttext,'');
end while;
return replace(replace(replace(sol_refined,'</li><li>','|'),'<li>',''),'</li>','');
End;
现在这被转换为雪花中的用户定义函数,我收到错误:
CREATE OR REPLACE FUNCTION FN_PARSE(originalcontent STRING)
RETURNS STRING
LANGUAGE SQL
AS
$$
Declare extracttext String;
sol String;
sol_refined String;
content String;
Begin
content := originalcontent;
while (REGEXP_INSTR(content, '<li>')>1) do
extracttext := SUBSTRING(content, REGEXP_INSTR(content, '<li>'), REGEXP_INSTR(content,'</li>')-REGEXP_INSTR(content, '<li>'))||'</li>';
IF (sol IS NULL) THEN
sol := extracttext;
ELSE
sol := sol || extracttext;
END IF;
IF (sol_refined IS NULL) THEN
sol_refined := CASE WHEN
DATEDIFF('month', GETDATE(), TRY_TO_DATE(SUBSTRING(RIGHT(extracttext, 15), 1, 10),'MM-DD-YYYY')) <= 3
THEN extracttext ELSE '' END;
ELSE
sol_refined := sol_refined || CASE WHEN
DATEDIFF('month', GETDATE(), TRY_TO_DATE(SUBSTRING(RIGHT(extracttext, 15), 1, 10),'MM-DD-YYYY')) <= 3
THEN extracttext ELSE '' END;
END IF;
content := replace(content,extracttext,'');
end while;
return replace(replace(replace(sol_refined,'</li><li>','|'),'<li>',''),'</li>','');
End;
$$;
我非常感谢您对此的帮助。谢谢你
Snowflake SQL 用户定义函数仅限于根据 SQL UDF 执行单个 SQL 表达式。比如:
CREATE FUNCTION area_of_circle(radius FLOAT)
RETURNS FLOAT
AS
$$
pi() * radius * radius
$$
;
对于更复杂的事情,您将需要 SQL 存储过程,或者使用 JavaScript、Python、Java 或 Scala 定义的 UDF。