キーワード:
・テキストの行数を数える
・functionの作り方
・Loopの使い方
drop function if exists util_getRowCount;
DELIMITER ///
CREATE DEFINER=`root`@`localhost` function util_getRowCount(target longtext)
returns varchar(1000)
-- returns decimal(11,0)
BEGIN
declare lineMaxCount int;
declare sLine VARCHAR(100);
declare retValue decimal(11,0);
declare lineCount int;
declare i int;
declare isComment int;
declare isBlank int;
declare lCodeCharCount int;
declare currentTarget longtext;
declare vDebug VARCHAR(10000);
-- 引数チェック
if CHAR_LENGTH(target) = 0 THEN
return 0;
END IF;
-- 変数初期化
set i = 0;
set lineCount = 0;
set vDebug = '';
set lCodeCharCount = 0;
-- 利用変数準備
select CHAR_LENGTH(target) - CHAR_LENGTH(REPLACE(target,'\n','')) +1 into lineMaxCount;
set currentTarget = REPLACE(target,'\r\n','\n');
set currentTarget = REPLACE(target,'\r','\n');
charLoopLabel: LOOP
-- increment
SET i = i + 1;
-- 抜ける条件
IF i > lineMaxCount THEN
LEAVE charLoopLabel;
END IF;
-- 行として判定する
set sLine = replace(substring_index(currentTarget,'\n',1),'\t',' ');
set isComment = 0;
set isBlank = 0;
-- コメント判定
if substr(trim(sLine),1,2)= '--' THEN
set isComment = 1;
end if;
-- 空行判定
if length(trim(REPLACE(sLine,'\t',''))) = 0 THEN
set isBlank = 1;
end if;
if (isComment = 0 and isBlank = 0) THEN
SET lineCount = lineCount + 1;
set lCodeCharCount = lCodeCharCount + CHAR_LENGTH(sLine);
end if;
-- 判定した行を取り除く
set currentTarget = substr(currentTarget,CHAR_LENGTH(sLine) + 2);
-- set vDebug = CONCAT(vDebug,isComment,isBlank,'xx',sLine,'_');
END LOOP charLoopLabel;
return CONCAT(lineCount , ',' , lCodeCharCount);
-- return lineCount;
-- set vDebug = CONCAT(vDebug,'__result__',lineCount);
-- return vDebug;
-- return CHAR_LENGTH(target);
end;
///
delimiter ;
-- select util_getRowCount('12345\n22345\n33345') AS '3';
-- select util_getRowCount('12345\n22345\n33345\n\n\n\n\n') AS '3';
-- select util_getRowCount('12345\n22345\n33345\n\n\n\n\n -- comment \n -- comment2\n44444') AS '4';
-- select util_getRowCount('日本語\n日本語2\n日本語3\n\n\n\n\n -- コメント1 \n -- comment2\n44444\n') AS '4';
0 件のコメント:
コメントを投稿