Thứ Năm, 7 tháng 6, 2012

Mấy cái hàm Ora thông dụng

TO_CHAR

Convert a numeric or date expression to a character String.
Syntax
      to_char(expression [,'format'] [,nls_format])

Key
   char      The DATE, NUMBER or expression to convert
   format    Format to use.
   nls_lang  The international language to use.
The format may be either a DATE format (YYYY=year, MM=month, DD=Day, HH=Hour, Mi=Minute )
or a NUMBER format (0999=include leading zero).

If no format is specified Oracle will use the default date format.
nls_format allows international formats to be applied.
TO_CHAR will convert NCHAR, NVARCHAR2, CLOB, or NCLOB data to the database character set.
Examples
SQL> Select to_char(sysdate, 'yyyy/mm/dd') FROM dual;
 '2010/12/24'

SQL> Select to_char(sysdate, 'FMMonth DD, YYYY') FROM dual;
 'June 9, 2005'

SQL> select to_char(sysdate,'HH24:MI:SS') "Time Now" from dual;
 '14:35:56'

SQL> Select to_char(1.234, '9999.9') FROM dual;
 '1.2'

SQL> Select to_char(1000.25, '9,999.99') FROM dual;
 '1,000.25'

SQL> Select to_char(1000.25, '$9,999.00') FROM dual;
 '$1,000.25'

SQL> Select to_char(25, '000099') FROM dual;
 '000025'

SQL> Select to_char(-50, 'PR999') FROM dual;
 '<50>'

SQL> Select to_char(17, 'RN99') FROM dual;
 'XVII'

SQL> Select to_char('01110' + 1) FROM dual;
 1111

SQL> Select to_char(timestamp, 'DD-MM-YYYY HH24:MI') FROM dual;
 31-12-2005 23.30
Convert a character string into an Oracle date, then convert back to a string with a different date format:
SQL> Select to_char(mydate,'DD-MON-RR HH12:MI') Short_Date_Time
 from (
   select to_date('1-MAR-2010 23:24','DD-MON-RRRR HH24:MI') mydate
   from dual
 );

TO_DATE

Convert an expression to a date value.
Syntax to_date(char[,'format'[,nls_lang]) Key char String expression that will be converted to a date format Date format to use. nls_lang The international language to use. to_date will convert either a character string or an expression into a date value.

The 'format' must be a valid DATE format: YYYY=year, MM=month, DD=Day, HH=Hour, Mi=Minute
If no format is specified Oracle will assume the default date format has been supplied in char.
Examples
to_date('29-Oct-09', 'DD-Mon-YY') to_date('10/29/09', 'MM/DD/YY') to_date('120109', 'MMDDYY') to_date('29-Oct-09', 'DD-Mon-YY HH:MI:SS') to_date('Oct/29/09', 'Mon/DD/YY HH:MI:SS') to_date('October.29.2009', 'Month.DD.YYYY HH:MI:SS') SQL> select * from sales where order_date > to_date('29-Oct-09', 'DD-Mon-YY'); To check that year 2000 dates are appearing correctly try the following:
SELECT to_char(add_months(to_date('01-JAN-1998', 'DD-MON-YYYY'),1 * 12),'DD-MON-YYYY') y1999, to_char(add_months(to_date('01-JAN-1998', 'DD-MON-YYYY'),2 * 12),'DD-MON-YYYY') y2000, to_char(add_months(to_date('01-JAN-1998', 'DD-MON-YYYY'),7 * 12),'DD-MON-YYYY') y2005, to_char(add_months(to_date('01-JAN-1998', 'DD-MON-YYYY'),52 * 12),'DD-MON-YYYY') y2050 FROM DUAL; -- Expected output -- Y1999 Y2000 Y2005 Y2050 -- ----------- ----------- ----------- ----------- -- 01-JAN-1999 01-JAN-2000 01-JAN-2005 01-JAN-2050
 

TO_NUMBER

Convert a string expression to a number
Syntax to_number(char[,'format'[,nls_lang]) Key char String expression that will be converted to a number format Date format to use. nls_lang The international language to use. You can convert a character or expression that contains a number into an actual number value.

The 'format' must be a valid Number format.

nls_lang allows international formats to be applied e.g. currency symbols and numeric chars.
ORA-01722: invalid number - error thrown if TO_NUMBER is passed a string that doesn't represent a number. See René Nyffenegger's safe_to_number function.
Examples
SQL> Select to_number('1234.64') from Dual;
1234.64
SQL> Select to_number('1234.64', '9999.9') from Dual;
1234.6
SQL> Select to_number('$99.64', 'L99D99') from Dual;
99.64

CASE and Width_Bucket Functions

Case Function
A flexible method of grouping data into even or unevenly sized buckets.
Very similar to DECODE
Syntax:
CASE WHEN <cond1> THEN <Value1>
     WHEN <cond2> THEN <Value2>
     [ELSE Value n ] END   
A single CASE statement can be selected (along with other columns), resulting in a vertical list of data buckets. Alternatively several case statements can be summed to display totals in a horizontal row:

 SELECT CASE WHEN sal>1000 THEN 'Over paid'
             ELSE 'Under paid' END
 FROM   emp;


 SELECT SUM(CASE WHEN SUM(amount) BETWEEN 0 AND 49 THEN 1 
            ELSE 0 END) AS "0-49",
        SUM(CASE WHEN SUM(amount) BETWEEN 50 AND 100
           THEN 1 ELSE 0 END) AS "50-100"
 FROM sales;
 
WIDTH_BUCKET Function
Divide a data set into buckets with an equal interval size.
e.g. Age = 0-20, 20-40, 40-60, 60-80…
This is known as an 'equiwidth histogram'.
Syntax:
WIDTH_BUCKET(column/expr, low boundary, high_boundary,
              bucket_count)

If you ask for (n) buckets you actually get (n+2) buckets
The extra 2 being for values above and below the high/low boundaries.

e.g.
SELECT last_name, salary,
       WIDTH_BUCKET(salary,3000,9000,3)

Will create 5 buckets:
Up_to_3000, 3000-5000, 5000-7000, 7000-9000, 9000+
When using WIDTH_BUCKET pay attention to the boundary values, each bucket will contain values equal to or greater than the lowest boundary of that bucket, so age ranges 0-20, 20-40… would actually be 0-19.99 and 20-39.999…

"Our team is well balanced. We have problems everywhere." - Tommy Prothro


mấy cái lụm lặt (SQL)

Oracle SQL Functions

Functions:
ABS(n)        Absolute value of number
ACOS(n)       arc cosine of n
ADD_MONTHS(date,num_months)
              Returns date + num_months
ASCII(char)   Converts char into a decimal ascii code
ASIN(n)       arc sine of n.
ATAN(n)       arc tangent of n. 
ATAN2(n.m)    arc tangent of n and m. 
AVG([DISTINCT]n)
              Averge value of 'n' ignoring NULLs

BETWEEN value AND value
              Where 'x' between 25 AND 100
BFILENAME('directory','filename')
              Get the BFILE locator associated with a physical LOB binary file.

CASE          Group the data into sub-sets.
CEIL(n)       Round n up to next whole number.
CHARTOROWID(char)
              Converts a Char into a rowid value.
CHR(n)        Character with value n
CONCAT(s1,s2) Concatenate string1 and string2
CONVERT(char_to_convert, new_char_set, old_char_set)
              Convert a  string from one character set to another.
COS(n)        Cosine of number
COSH(n)       Hyperbolic Cosine of number
COUNT(*)      Count the no of rows returned
COUNT([DISTINCT] expr)
              Count the no of rows returned by expr
CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP

DECODE        IF x THEN return y ELSE return z
DENSE_RANK    Calculate the rank of a value in a group
DEREF(e)      Return the object reference of argument e. 
DUMP(expr,fmt[,start,length])
              Convert to dec/hex/oct and display char set

EMPTY_BLOB    Return an empty LOB locator (use to empty a column or variable)
EMPTY_CLOB    Return an empty LOB locator (use to empty a column or variable)
EXISTS        Return TRUE if a subquery returns at least one row
EXP(n)        Exponential (e to 'n'th power)
EXTRACT       Extract part of a DATE (Year,Month,Day,Second,etc)

FLOOR(n)      Round n down to the next whole number.

GREATEST(expression, expression…)
              Returns the largest in a list of expressions.
GROUPING      Grouping for superaggregate rows=NULL
              (see GROUP BY ROLLUP/CUBE)

HEXTORAW(char) Convert char containing hex digits to a raw value.

IN (list of comma separated values)
              Effectively a shorthand for ['x' = y OR 'x' = z…] i.e.
              Where 'x' IN ('sales','marketing','recruitment')
INITCAP(char) String with Initial Capitals
INSTR(str, chars[,s[,n]])
              Find the 'n'th occurence of 'chars' in 'str'
              Starting at position 's'
              n and s default to 1
INSTRB (str, chars[,s[,n]])
              The same as INSTR, except that 's' and the return value are expressed in bytes,
              use for double-byte char sets.
IS NULL       Check for NULL (empty) values  (Select * from demo Where x IS NULL;)
IS NOT NULL   Check for items that contain a value (Select * from demo Where x IS NOT NULL;)

LAST_DAY(date)Returns the last day of month in Date
LEAST(expression, expression…)
              Returns the smallest in a list of expressions
LENGTH(char)  Returns the number of characters in char
LENGTHB(char) Returns the number of bytes in char (use for double-byte char sets)
LIKE wildcard/value
              Wildcards are [% = any chars] [ _ = any one char]
              Where 'x' LIKE 'smith%' [will find 'Smithson']
              Where 'x' LIKE 'smith_' [will find 'Smithy']
LN(n)         Natural Log of n, where n>0
LOG(b,n)      log of n, base b
LOWER(char)   Returns character string in lowercase
LPAD(char, n[,PadChar])
              Left Pad char with n spaces [or PadChars]
LTRIM(char[,set])
              Left Trim char - remove leading spaces [or char set]

MAKE_REF(table,key)
              Create a REF to a row of an OBJECT view/table
MAX([DISTINCT] expr)
              Maximum value returned by expr
MIN([DISTINCT] expr)
              Minimum value returned by expr
MOD(x,y)      Remainder of x divided by y
MONTHS_BETWEEN(end_date, start_date)
              Number of months between the 2 dates (integer)

NEW_TIME(date, zone1, zone2)
              Convert between GMT and US time zones (but not CET)
NEXT_DAY(date,day_of_week)
              '12-OCT-01','Monday' will return the next Mon after 12 Oct
NLS_CHARSET_DECL_LEN (bytecount,charset)
              Returns the declaration width (no of chars) of an NCHAR column
NLS_CHARSET_ID(varchars)
              Returns the char set ID given a charset name
NLS_CHARSET_NAME(charset_id)
              Returns the char set name given a charset id
NLS_INITCAP(char[,'NLS_SORT = sort_sequence'])
              Returns char in Initial Caps, using an NLS sort_sequence
              either the session default or specified directly
NLS_LOWER(char[,'NLS_SORT = sort_sequence'])
              Returns char in lower case, using an NLS sort_sequence
              either the session default or specified directly
NLSSORT(char[,'NLS_SORT = sort_sequence'])
              Return the string of bytes used to sort char, using an NLS sort_sequence
              either the session default or specified directly
NLS_UPPER(char[,'NLS_SORT = sort_sequence'])
              Returns char in UPPER case, using an NLS sort_sequence
              either the session default or specified directly
NVL(expression, value_if_null)
              If expression is null, returns value_if_null; if expression is not null, returns expression.
              The arguments can have any datatype (Oracle will perform implicit conversion where needed).
PERCENT_RANK  Calculate the percent rank of a value in a group.
POWER(m,n)    m raised to the nth power

RANK          Calculate the rank of a value in a group
RAWTOHEX(raw) Convert raw to a character value containing its hex equivalent
REF(table_alias)
              Returns a REF value for an object instance (bound to the variable or row.)
              The table alias (correlation variable) is associated with
              one row of an object table or an object view in an SQL statement.
REFTOHEX(ref) Convert ref (object type) to a char value containing its hex equivalent.
REPLACE(char, search_str[, replace_str])
              ANSI alternative to decode() Replace every occurrence of search_str
              with replace_str, replace_str defaults to null.
ROUND(n,d)    n rounded to d decimal places (d defaults to 0)
ROUND(date,fmt)
              date rounded to fmt
ROWIDTOCHAR(rowid)
              Convert a rowid value to VARCHAR2
ROW_NUMBER    Assign a unique number to each row of results. 
RPAD(char, n[,PadChar])
              Right Pad char with n spaces [or PadChars]
RTRIM(char[,set])
              Right Trim char - remove trailing spaces [or char set]

SIGN(n)       positive = 1, zero = 0, negative = -1
SIN(n)        Sine of n in Radians.
SINH(n)       Hyperbolic Sine of n in Radians.
SOUNDEX(char) Returns a char value representing the sound of the words.
SQRT(n)       Square Root (returns NULL for negative no's)
STDDEV([DISTINCT] n)
              Standard deviation of n.
SUBSTR(char, s[,l])
              A substring of char, starting at character s, length l.
SUBSTRB(char, s[,l])
              A substring of char, starting at character s, length l
              The same as SUBSTR, except that 's', 'l' and the return value are expressed in bytes,
              use for double-byte char sets.
SUM([DISTINCT] n)
              Sum of values of n, ignoring NULLs
SYS_CONTEXT('namespace','attribute_name')
              Examine the package associated with the context namespace 
              Possible attributes are: NLS_TERRITORY, NLS_CURRENCY, NLS_CALENDAR 
              NLS_DATE_FORMAT, NLS_DATE_LANGUAGE, NLS_SORT, SESSION_USER, CURRENT_USER
              CURRENT SCHEMAID,SESSION_USERID, CURRENT_USERID, CURRENT_SCHEMA
              note: CURRENT_USER may be different from SESSION_USER within a stored procedure
              (e.g an invoker-rights procedure).  
SYS_CONTEXT ('USERENV','IP_ADDRESS')
SYS_GUID()    Returns a globally unique identifier (16 byte RAW value)
SYSDATE       The current system date & time

TAN(n)        Tangent of n in Radians
TANH(n)       Hyperbolic tangent of n in Radians
TO_BLOB(Raw_col)  Convert LONG RAW and RAW values to BLOB
TO_CHAR       Convert to a character String
TO_CLOB       Convert character or NCLOB values to the database character set.
TO_DATE       Convert to date value
TO_LOB(long)  Convert LONG values to CLOB or NCLOB values
              or convert LONG RAW values to BLOB values
TO_MULTI_BYTE(char)
              Convert single-byte char to multi-byte char
TO_NCHAR(expr) Convert a TEXT expression, date, or number to NTEXT in a specified format.
               Mostly used to format output data.
TO_NCLOB      Convert any character string (including LOBs) to the national character set.
TO_NUMBER     Convert to numeric format
TO_SINGLE_BYTE(char)
              Convert multi-byte char to single-byte character.
TO_TIME       Convert to time value
TO_TIME_TZ    Convert to time zone
TO_TIMESTAMP  Convert to timestamp 
TO_TIMESTAMP_TZ
TO_YMINTERVAL Convert a character string to an INTERVAL YEAR TO MONTH type
TRANSLATE('char','search_str','replace_str')
              Replace every occurrence of search_str with replace_str
              unlike REPLACE() if replace_str is NULL the function returns NULL
TRANSLATE (text USING charset)
              Convert text into a specific character set
              Use this instead of CONVERT() if either the input or output datatype
              is NCHAR or NVARCHAR2.
TRIM(LEADING|TRAILING|BOTH trim_char FROM trim_source)
              Return trim_source as a VARCHAR2 with leading/trailing items removed
              trim_char defaults to a space ' ' but may be numeric or char 'A' 
TRUNC(i,d)    Truncate i to d decimal places (d defaults to 0)
TRUNC(date,fmt) Truncate Date to nearest fmt.
UID           User id (a unique number)
UPPER(char)   Return characters in uppercase
USER          Return the current Username
USERENV('option')
              Can return any of the options: ENTRYID, SESSIONID,
              TERMINAL, LANGUAGE, ISDBA, LANG, INSTANCE, CLIENT_INFO

VALUE(correlation_variable)
              Return the object instance for a row of an object table 
              as associated with the correlation_variable (table alias)
VARIANCE([DISTINCT] n)
              Variance of n, ignoring NULLs
VSIZE(expr)   Value Size, returns the number of bytes used by each row of expr.
Examples
Return the left 4 characters from the column prod_code, like a left() function in other languages:
SQL> select substr(prod_code,1,4) from sales;
Return the right 3 characters from the column prod_code, like a right() function in other languages:
SQL> select substr(prod_code,-3) from sales;
Return the leftmost 2 digits of idnum:
SQL> select substr(to_char(idnum),1,2) from mytable;
This page is not an exhaustive list of all the functions available - to find a complete list of functions for a particular release of Oracle see docs.oracle.com or run this query:

SELECT distinct object_name
FROM all_arguments
WHERE package_name = 'STANDARD';


_____________________________________________________
cái ở trên copy cho đủ thôi, đọc chắc cũng lười, haha, mấy cái này hay sử dụng nè:

__To_char('x','00000') : cái này mạnh kinh. so với SQL server có lẽ cái này hữu dụng nhất, dùng để định dạng 1 chuỗi cần xuất ra. Có thể định dạng chuỗi ngày tháng, chuỗi số, ký tự theo 1 định dạng nhất định....
VD như to_char('x','0000')=000x, hay to_char(date,'ddmmyyyy')=ngày tháng năm theo chuẩn. Cái này trong SQL cũng có ...

__Lpad('x',5,'0') có nghĩa là thêm vào bên trái chữ x những số 0 sao cho tổng ký tự là 5 ký tự
tương tự với Rpad()

__Replace() cái này thì quen rồi :))

__ || cộng gộp hai chuỗi .

Thứ Tư, 6 tháng 6, 2012

Một số hàm xử lý chuỗi trong sql

Một số hàm xử lý chuỗi trong sql



SQL
Trong sql có lẽ chúng ta cũng sử dụng nhiều các hàm xử lý chuỗi. Dưới đây là các hàm xử lý chuỗi trong sql

- ASCII
Hàm này trả về giá trị ASCII của keyboard ví dụ (@,R,9,*)
Cú pháp- ASCII ( character)
Ví dụ:
SELECT ASCII('a') -- giá trị trả về= 97
SELECT ASCII('b') -- giá trị trả về= 98
SELECT ASCII('c') -- giá trị trả về= 99
SELECT ASCII('A') -- giá trị trả về= 65
SELECT ASCII('B') -- giá trị trả về= 66
SELECT ASCII('C') -- giá trị trả về= 67
SELECT ASCII('1') -- giá trị trả về= 49
SELECT ASCII('2') -- giá trị trả về= 50
SELECT ASCII('3') -- giá trị trả về= 51
SELECT ASCII('4') -- giá trị trả về= 52
SELECT ASCII('5') -- giá trị trả về= 53
- SPACE
Hàm này trả về khoảng trống trong câu lệnh sql
Cú pháp - SPACE ( integer)
Ví dụ:
SELECT ('SQL') + SPACE(0) + ('TUTORIALS')-- giá trị trả về= SQLTUTORIALS
SELECT ('SQL') + SPACE(1) + ('TUTORIALS')-- giá trị trả về = SQL TUTORIALS
- CHARINDEX
Trả về vị trí được tìm thấy của một chuỗi trong chuỗi cha
Cú pháp - CHARINDEX ( string1, string2 [ , start_location ] )
Ví dụ:
SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial')-- Value = 27
SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial', 20)-- Value = 27
SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial', 30)-- Value = 0 (bởi vì giá trị bắt đầu truyền vào từ ký tự 30 trở đi)
- REPLACE
Hàm thay thế chuỗi
Ví dụ:
Cú pháp- REPLACE ( 'string1' , 'string2' , 'string3' )
SELECT REPLACE('All Function' , 'All', 'SQL')-- Value = SQL Function
- UPPER, LOWER
Hàm chuyển đổi thành chữ hoa và chữ thường
Ví dụ:
Cú pháp
- UPPER( 'string1')
- LOWER( 'string1')
SELECT UPPER('Khong con mua thu')-- Value = 'KHONG CON MUA THU'
SELECT LOWER('kHONG CON MUA THU')-- Value = 'khong con mua thu'

- LEFT,RIGHT,SUBSTRING
Hàm cắt chuỗi bên trái, phải và ở giữa
Ví dụ:
Cú pháp
- LEFT( 'string1', số kí tự)
- RIGHT( 'string1', số kí tự)
- SUBSTRING ( 'string1', vị trí, số kí tự)
SELECT LEFT('Khong con mua thu',5)-- Value = 'Khong'
SELECT RIGHT('kHONG CON MUA THU',3)-- Value = 'THU'
SELECT SUBSTRING ('kHONG CON MUA THU',6,3)-- Value = 'CON'

- LTRIM, RTRIM
Loại bỏ khoảng trắng bên trái, bên phải
Ví dụ:
Cú pháp
- LTRIM( 'string1')
- RTRIM ( 'string1')
SELECT LTRIM(' Khong con mua thu')-- Value = 'Khong con mua thu'
SELECT RTRIM ('kHONG CON MUA THU ')-- Value = 'kHONG CON MUA THU'

- LEN
Trả về số ký tự trong chuỗi
Ví dụ:
Cú pháp
- LEN( 'string')
SELECT LEN('Khong con mua thu')-- Value = 17

- REVERSE
Đảo chuối
Ví dụ:
Cú pháp
- REVERSE( 'string')
SELECT REVERSE('Khong con mua thu')-- Value = 'uht aum noc gnohK'

- STUFF
Với cú pháp hàm STUFF bên dưới có kết quả trả về là một chuỗi mới sau khi đã hủy bỏ một số ký tự hiện có và thêm vào một chuỗi con khác tại vị trí vừa hủy bỏ
Ví dụ:
Cú pháp
- STUFF ( 'string',vị trí, chiều dài, chuỗi con)
vị trí: là một số nguyên chỉ định vị trí bắt đầu hủy bỏ các ký tự bên trong chuỗi nguồn.
chiều dài: là một số nguyên chỉ định bao nhiêu ký tự sẽ bị hủy bỏ trong chuỗi nguồn đếm từ bên trái vị trí chỉ định.
SELECT STUFF ('123456789',4,3,'ABDCEF')-- Value = '123ABCDEF789'

Thứ Hai, 4 tháng 6, 2012

Công việc mới



1/6, ngày quốc tế thiếu nhi thì mình nhận được việc mới, công việc khá thử thách vì nó là những mảng mình chưa bao giờ làm (chắc tại mình làm ít quá đây mà keke) là mảng về triển khai, mảng ngân hàng, kế toán , oracle, java..... nói chung là zin nguyên con :))




.. viết tạm mấy dòng lấy cảm hứng tối viết tiếp..

\..quái, sao hnay lại có hứng viết blog vậy ta :))