主键字母自动生成函数
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                主键字母自动生成函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                
                            
                            
                            -- 動態生成字母方式主鍵,A-Z 大于Z自動進位【26進制數值表示】-- 參數:動態查詢表和主鍵列
create or replace function charkey (tabName char, pkName char) return char
asv_key varchar2(4);        -- 表中查詢出當前主鍵列最大值v_char varchar2(4) := ''; -- 輸出用變量v_len number(1);          -- 查詢出最大值字符串長度v_i number(1);            -- 循環控制變量v_c char(1);              -- 提取單個字符變量v_flag number(1) := 1;    -- 是否'進位'變量v_count number;           -- 查詢表中記錄總數
begin-- 查詢表中記錄數execute immediate 'select count(1) from ' || tabName into v_count;-- 如果表中沒有記錄,則返回'A'if (v_count = 0) then v_char := 'A';return v_char;end if;-- 獲取指定表中主鍵列當前最大值execute immediate 'select ' || pkName || ' from ' ||'(select rownum r, t.' || pkName || ' from ' ||'(select ' || pkName || ' from ' || tabName || ' order by length(' || pkName || ') desc, ' || pkName || ' desc) t) where r < 2'into v_key;-- 字符串長度v_len := length(v_key);-- 循環控制變量v_i := v_len;-- 從最后一個字符開始,向前循環遍歷while v_i >= 1 loopv_c := substr(v_key, v_i, 1);-- 如果需要進位,當前字符+1if(v_flag = 1) thenv_c := chr(ascii(v_c)+1);v_flag := 0;end if;-- 當前字符超出上限if( ascii(v_c) > ascii('Z')) thenv_c := 'A';v_flag := 1;end if;v_char := v_c || v_char;v_i := v_i - 1;end loop;-- 如果遇到ZZ情況,需要補充一位'A'if(v_flag = 1) thenv_char := 'A' || v_char;end if;  return v_char;
end;-- 測試表
create table testtab
(id varchar2(4) primary key,val number(4)
);-- 測試通過函數動態生成主鍵插入數據
declarev_count number(9) := 1;
beginwhile v_count <= 30 loopinsert into testtab values(charkey('testtab','id'), 1);  v_count := v_count + 1;end loop;
end;select * from testtab;
 
                            
                        
                        
                        總結
以上是生活随笔為你收集整理的主键字母自动生成函数的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: mysql中int、bigint、sma
- 下一篇: Dynamic_Performance_
