我确实有一个问题要解决,我需要为每3个字符插入下划线
样本:从→123456789比;123年_456_789
您可能想使用"self-defined"函数,可以在任何需要的地方重用,无论是在查询中还是在触发器中。这是一个快速而肮脏的例子,适用于我的SQL Anywhere v17数据库。取决于sybase"您可能需要调整它或使用不同的内置函数(请参阅参考- Sybase文档清楚地说明了可用的内置函数)。为了简单起见,我只使用了VARCHAR(100):
CREATE OR REPLACE FUNCTION FormatPositionedUnderscores(par_input VARCHAR(100))
RETURNS VARCHAR(100)
DETERMINISTIC
BEGIN
DECLARE ls_formatted VARCHAR(100);
DECLARE li_length INTEGER;
DECLARE li_current INTEGER DEFAULT 0;
DECLARE ls_current_char CHAR(1);
-- trim it and calculate the length of the string
SET par_input = TRIM(par_input);
SET li_length = CHAR_LENGTH(par_input);
-- iterate over every character
WHILE li_current < li_length LOOP
SET li_current = li_current + 1;
-- get the current character
SET ls_current_char = SUBSTRING(par_input, li_current, 1);
-- append it to the resulting string
SET ls_formatted = ls_formatted || ls_current_char;
-- if we have 3 characters "full" (and are not at the end)
-- append an underscore
IF MOD(li_current, 3) = 0 AND li_current < li_length THEN
SET ls_formatted = ls_formatted || '_';
END IF;
END LOOP;
-- return the resulting string
RETURN ls_formatted;
END;
在查询中使用SELECT FormatPositionedUnderscores('123456789)
,您将得到123_456_789
。