TO_CHAR Date Format in Informatica To_Char(Date_column,Format)

0

Format String

Description

AM, A.M.,

 

PM, P.M.

Meridian indicator. Use any of these format strings to specify AM and PM hours. AM and PM return the same values as A.M. and P.M.

D

Day of week (1-7), where Sunday equals 1.

DAY

Name of day, including up to nine characters (for example, Wednesday).

DD

Day of month (01-31).

DDD

Day of year (001-366, including leap years).

DY

Abbreviated three-character name for a day (for example, Wed).

HH, HH12

Hour of day (01-12).

HH24

Hour of day (00-23), where 00 is 12AM (midnight).

J

Modified Julian Day. Converts the calendar date to a string equivalent to its Modified Julian Day value, calculated from Jan 1, 4713 00:00:00 BC. It ignores the time component of the date. For example, the expression TO_CHAR( SHIP_DATE, 'J' ) converts Dec 31 1999 23:59:59 to the string 2451544.

MI

Minutes (00-59).

MM

Month (01-12).

MONTH

Name of month, including up to nine characters (for example, January).

MON

Abbreviated three-character name for a month (for example, Jan).

MS

Milliseconds (0-999).

NS

Nanoseconds (0-999999999).

Q

Quarter of year (1-4), where January to March equals 1.

RR

Last two digits of a year. The function removes the leading digits. For example, if you use 'RR' and pass the year 1997, TO_CHAR returns 97. When used with TO_CHAR, 'RR' produces the same results as, and is interchangeable with, 'YY.' However, when used with TO_DATE, 'RR' calculates the closest appropriate century and supplies the first two digits of the year.

SS

Seconds (00-59).

SSSSS

Seconds since midnight (00000 - 86399). When you use SSSSS in a TO_CHAR expression, the Integration Service only evaluates the time portion of a date. For example, the expression TO_CHAR(SHIP_DATE, 'MM/DD/YYYY SSSSS') converts 12/31/1999 01:02:03 to 12/31/1999 03783.

US

Microseconds (0-999999).

Y

Last digit of a year. The function removes the leading digits. For example, if you use 'Y' and pass the year 1997, TO_CHAR returns 7.

YY

Last two digits of a year. The function removes the leading digits. For example, if you use 'YY' and pass the year 1997, TO_CHAR returns 97.

YYY

Last three digits of a year. The function removes the leading digits. For example, if you use 'YYY' and pass the year 1997, TO_CHAR returns 997.

YYYY

Entire year portion of date. For example, if you use 'YYYY' and pass the year 1997, TO_CHAR returns 1997.

W

Week of month (1-5), where week 1 starts on the first day of the month and ends on the seventh, week 2 starts on the eighth day and ends on the fourteenth day. For example, Feb 1 designates the first week of February.

WW

Week of year (01-53), where week 01 starts on Jan 1 and ends on Jan 7, week 2 starts on Jan 8 and ends on Jan 14, and so on.

- / . ; :

Punctuation that displays in the output. You might use these symbols to separate date parts. For example, you create the following expression to separate date parts with a period: TO_CHAR( DATES, 'MM.DD.YYYY' ).

"text"

Text that displays in the output. For example, if you create an output port with the expression: TO_CHAR( DATES, 'MM/DD/YYYY "Sales Were Up"' ) and pass the date Apr 1 1997, the function returns the string '04/01/1997 Sales Were Up'. You can enter multibyte characters that are valid in the repository code page.

""

Use double quotation marks to separate ambiguous format

 

Session to run once in a Week

0
Problem :

  1. There is a workflow having 3 sessions in sequence A à B à C. We want session 'C ' to run weekly once i.e only Friday,  If it is any other day in a week we need to skip executing.  A & B sessions need to run everyday in a week. How would you do that any suggestions please.

We Suggested:

Just add the below condition on the link between Session B and Session C :

 

to_Char(sysdate,'D')='6'


'6' means -- Friday 


Make Sure :  High lighted option is deselected .



 


Frequently Used Meta Queries - Oracle

0

While Oracle doesn't implement the INFORMATION_SCHEMA SQL-92 standard, there are several methods to get metadata information, such as using SQL *Plus and DESCRIBE, or using the the PL/SQL metadata API and the DBMS_METADATA package (available since Oracle 9i), or using the data dictionary views.
In this tutorial, we're going to see how to get metadata information from our database using the Oracle Data Dictionary views ("select * from dict" for a full listing).

Oracle INFORMATION_SCHEMA - extracting Oracle metadata, by Lorenzo Alberton

Test data

We need a few sample tables, indices and views to test the following queries, so let's create them. We also create a sample TRIGGER, a STORED PROCEDURE and a FUNCTION.

-- sample data to test Oracle INFORMATION_SCHEMA     -- TABLE TEST  CREATE TABLE TEST (    TEST_NAME CHAR(30) NOT NULL,    TEST_ID INTEGER DEFAULT 0 NOT NULL,    TEST_DATE TIMESTAMP NOT NULL  );  ALTER TABLE TEST ADD CONSTRAINT PK_TEST PRIMARY KEY (TEST_ID);     -- TABLE TEST2 with some CONSTRAINTs and an INDEX  CREATE TABLE TEST2 (    ID INTEGER NOT NULL,    FIELD1 INTEGER,    FIELD2 CHAR(15),    FIELD3 VARCHAR(50),    FIELD4 INTEGER,    FIELD5 INTEGER,    ID2 INTEGER NOT NULL  );  ALTER TABLE TEST2 ADD CONSTRAINT PK_TEST2 PRIMARY KEY (ID2);  ALTER TABLE TEST2 ADD CONSTRAINT TEST2_FIELD1ID_IDX UNIQUE (ID, FIELD1);  ALTER TABLE TEST2 ADD CONSTRAINT TEST2_FIELD4_IDX UNIQUE (FIELD4);  CREATE INDEX TEST2_FIELD5_IDX ON TEST2(FIELD5);     -- TABLE NUMBERS  CREATE TABLE NUMBERS (    NUM INTEGER DEFAULT '0' NOT NULL,    EN CHAR(100) NOT NULL,    FR CHAR(100) NOT NULL  );     -- TABLE NEWTABLE  CREATE TABLE NEWTABLE (    ID INT DEFAULT 0 NOT NULL,    SOMENAME VARCHAR (12),    SOMEDATE TIMESTAMP NOT NULL  );  ALTER TABLE NEWTABLE ADD CONSTRAINT PKINDEX_IDX PRIMARY KEY (ID);  CREATE SEQUENCE NEWTABLE_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE;     -- VIEW on TEST  CREATE VIEW testview(    TEST_NAME,    TEST_ID,    TEST_DATE  ) AS  SELECT *  FROM TEST  WHERE TEST_NAME LIKE 't%';     -- VIEW on NUMBERS  CREATE VIEW numbersview(    NUM,    TRANS_EN,    TRANS_FR  ) AS  SELECT *  FROM NUMBERS  WHERE NUM > 100;     -- TRIGGER on NEWTABLE  CREATE OR REPLACE TRIGGER TEST_TRIGGER  AFTER UPDATE ON NEWTABLE  REFERENCING NEW AS NEW OLD AS OLD  FOR EACH ROW  BEGIN    INSERT INTO NEWTABLE (id, somename, somedate) VALUES (:new.id+1, :new.somename, :new.somedate);  END TEST_TRIGGER;     -- SAMPLE FUNCTION  CREATE FUNCTION sum_two_integers(a IN INT, b IN INT)  RETURN INT AS  BEGIN      RETURN a + b;  END;     -- SAMPLE STORED PROCEDURE  CREATE OR REPLACE PROCEDURE count_numbers_by_lang(var_lang in varchar2, var_num out integer)  IS  var_temp_n INTEGER;  BEGIN  SELECT COUNT(DISTINCT var_lang)    INTO var_temp_n    FROM NUMBERS  WHERE var_lang IS NOT NULL;  var_num := var_temp_n;  return;  END;     -- TABLEs for testing CONSTRAINTs  CREATE TABLE testconstraints (    someid integer NOT NULL,    somename character varying(10) NOT NULL,    CONSTRAINT testconstraints_id_pk PRIMARY KEY (someid)  );  CREATE TABLE testconstraints2 (    ext_id INTEGER NOT NULL,    modified DATE,    uniquefield VARCHAR(10) NOT NULL,    usraction INTEGER NOT NULL,    CONSTRAINT unique_2_fields_idx UNIQUE (modified, usraction),    CONSTRAINT uniquefld_idx UNIQUE (uniquefield),    CONSTRAINT testconstraints_id_fk FOREIGN KEY (ext_id)      REFERENCES TESTCONSTRAINTS (someid) ON DELETE CASCADE  );

List TABLEs

Here's the query that will return the names of the tables defined in the current database:

SELECT table_name    FROM user_tables;      -- or     SELECT table_name    FROM tabs;

List VIEWs

Here's the query that will return the names of the VIEWs defined in the current database:

SELECT view_name    FROM user_views;

List users

NB: you'll need DBA access rights to execute the following query:

SELECT username    FROM dba_users;

List table fields

Here's the query that will return the names of the fields of the TEST2 table:

SELECT column_name      FROM user_tab_columns     WHERE table_name='TEST'  ORDER BY column_id

Detailed table field info

If you want some more info about the field definitions, you can retrieve a larger subset of the fields available in the schema:

SELECT column_id "ordinal_position",           column_name,           data_type,           nullable,           data_default "default",           COALESCE(data_precision, data_length) "length",           data_scale "scale"      FROM all_tab_columns     WHERE table_name = 'TEST2'  ORDER BY column_id;

List INDICES

Here's the query that will return the names of the INDICES defined in the TEST2 table. NB: the CONSTRAINTs are not listed

SELECT index_name name    FROM user_indexes   WHERE table_name = 'TEST2'     AND generated = 'N';

Detailed INDEX info

If you want to know which table columns are referenced by an index, try with this query:

SELECT aic.index_name,            aic.column_name,            aic.column_position,            aic.descend,            aic.table_owner,            CASE alc.constraint_type              WHEN 'U' THEN 'UNIQUE'              WHEN 'P' THEN 'PRIMARY KEY'              ELSE ''            END AS index_type       FROM all_ind_columns aic  LEFT JOIN all_constraints alc         ON aic.index_name = alc.constraint_name        AND aic.table_name = alc.table_name        AND aic.table_owner = alc.owner      WHERE aic.table_name = 'TEST2'            -- table name      --AND aic.table_owner = 'HR'              -- table owner      --AND aic.index_name = 'TEST2_FIELD5_IDX' -- index name   ORDER BY column_position;

List CONSTRAINTs

Here's the query that will return the names of the CONSTRAINTs defined in the TEST2 table:

SELECT constraint_name name    FROM user_constraints   WHERE table_name = 'TEST2';

Detailed CONSTRAINT info

If you want to retrieve detailed info from any constraint (fields, type, rules, referenced table and fields for FOREIGN KEYs, etc.) given its name and table, here's the query to do so:

SELECT alc.constraint_name,            CASE alc.constraint_type              WHEN 'P' THEN 'PRIMARY KEY'              WHEN 'R' THEN 'FOREIGN KEY'              WHEN 'U' THEN 'UNIQUE'              WHEN 'C' THEN 'CHECK'            END "constraint_type",            alc.DELETE_RULE "on_delete",            CASE alc.deferrable WHEN 'NOT DEFERRABLE' THEN 0 ELSE 1 END "deferrable",            CASE alc.deferred WHEN 'IMMEDIATE' THEN 1 ELSE 0 END "initially_deferred",            alc.search_condition,            alc.table_name,            cols.column_name,            cols.position,            r_alc.table_name "references_table",            r_cols.column_name "references_field",            r_cols.position "references_field_position"       FROM all_cons_columns cols  LEFT JOIN all_constraints alc         ON alc.constraint_name = cols.constraint_name        AND alc.owner = cols.owner  LEFT JOIN all_constraints r_alc         ON alc.r_constraint_name = r_alc.constraint_name        AND alc.r_owner = r_alc.owner  LEFT JOIN all_cons_columns r_cols         ON r_alc.constraint_name = r_cols.constraint_name        AND r_alc.owner = r_cols.owner        AND cols.position = r_cols.position      WHERE alc.constraint_name = cols.constraint_name        AND alc.constraint_name = 'TESTCONSTRAINTS_ID_FK'        AND alc.table_name = 'TESTCONSTRAINTS2';

The above query has the small drawback of being slow, with the multiple self-join on theall_cons_columns and all_constraints views. If you know a faster query to get the same information, please let me know. If you have DBA access rights, you can run the following query instead, it should be considerably faster:

SELECT c.name "constraint_name",         decode(cd.type#, 1, 'CHECK', 2, 'PRIMARY KEY', 3, 'UNIQUE', 4, 'FOREIGN KEY', 5, 'V', 6, 'O', 7, 'C', '?') "constraint_type",         decode(cd.type#, 4, decode(cd.refact, 1, 'CASCADE', 2, 'SET NULL', 'NO ACTION'), NULL) "delete_rule",         decode(cd.type#, 5, 'ENABLED', decode(cd.enabled, NULL, 'DISABLED', 'ENABLED')) "status",         decode(bitand(cd.defer, 1), 1, 'DEFERRABLE', 'NOT DEFERRABLE') "deferrable",         decode(bitand(cd.defer, 2), 2, 'DEFERRED', 'IMMEDIATE') "deferred",         cd.condition "search_condition",         o.name "table_name",         decode(ac.name, null, col.name, ac.name) "column_name",         cc.pos# "position",         rc.name "r_constraint_name",         ro.name "references_table",         decode(rac.name, null, rcol.name, rac.name) "references_field",         rcc.pos# "references_field_position"    FROM sys.con$ c,         sys.col$ col,         sys.ccol$ cc,         sys.cdef$ cd,         sys.obj$ o,         sys.con$ rc,         sys.attrcol$ ac,         sys.col$ rcol,         sys.ccol$ rcc,         sys.cdef$ rcd,         sys.obj$ ro,         sys.attrcol$ rac   WHERE c.con# = cd.con#     AND cd.type# != 12 /* don't include log groups */     AND cd.con# = cc.con#     AND cc.obj# = col.obj#     AND cc.intcol# = col.intcol#     AND cc.obj# = o.obj#     AND c.owner# = userenv('SCHEMAID')     AND col.obj# = ac.obj#(+)     AND col.intcol# = ac.intcol#(+)     AND cd.rcon# = rc.con#(+)     AND rc.con# = rcd.con#     AND rcd.type# != 12 /* don't include log groups */     AND rcd.con# = rcc.con#     AND rcc.obj# = rcol.obj#     AND rcc.intcol# = rcol.intcol#     AND rcc.obj# = ro.obj#     AND rc.owner# = userenv('SCHEMAID')     AND rcol.obj# = rac.obj#(+)     AND rcol.intcol# = rac.intcol#(+)     AND c.name = 'TESTCONSTRAINTS_ID_FK'

List sequences

SEQUENCE is an object that automatically generate sequence numbers. A SEQUENCE is often used to ensure a unique value in a PRIMARY KEY that must uniquely identify the associated row.

SELECT sequence_name    FROM user_sequences;

List TRIGGERs

SELECT trigger_name    FROM user_triggers;    -- List only the triggers for a given table:    SELECT DISTINCT trigger_name    FROM user_triggers   WHERE table_name = 'NEWTABLE';

Detailed TRIGGER info

Show more information about the trigger definition:

SELECT trigger_name,         table_name,         trigger_body,         trigger_type,         triggering_event trigger_event,         description trigger_comment,         1 trigger_enabled,         when_clause    FROM user_triggers   WHERE trigger_name = 'TEST_TRIGGER';

List FUNCTIONs

SELECT name    FROM user_source   WHERE line = 1     AND type = 'FUNCTION';

List STORED PROCEDUREs

SELECT DISTINCT procedure_name   FROM all_procedures;     -- list only the SP owned by current user:     SELECT *    FROM all_procedures   WHERE owner = 'username';

Regular Expression - Data Enclosed within double quotes

0
With A As
  (Select 'when "EDW"."Dim - Store Operations Metrics"."Attribute Value"  = ''StaffHours''  then ''18016'' '''  As Text From Dual),
b as (
SELECT 
    Text, 
    REGEXP_SUBSTR(text, '("[[:print:]]*"\.)+"[[:print:]]*"',1,level) part, 
    level l
  FROM a
  Connect By 
    REGEXP_SUBSTR(text, '("[[:print:]]*"\.)+"[[:print:]]*"',1,level) is not null
  )
Select Text,Listagg(B.Part,' ') Within Group (Order By L)
from b group by text;   

Date Conversion in SQL Server

0
Open SQL Server and Open a new SQL Query :-


DECLARE @DateTime DATETIME
SELECT @DateTime =getdate()

/*For mm/dd/yyyy format*/
Select CONVERT(VARCHAR(10),@DateTime ,101) as Date

/*For yyyy.mm.dd format*/
Select CONVERT(VARCHAR(10),@DateTime ,102) as Date

/*For dd/mm/yyyy format*/
SELECT CONVERT(VARCHAR(10),@DateTime ,103) AS Date

/*For dd.mm.yyyy format*/
SELECT CONVERT(VARCHAR(10),@DateTime ,104) AS Date

/*For dd-mm-yyyy format*/
SELECT CONVERT(VARCHAR(10),@DateTime ,105) AS Date

/*For hh:mi:ss format*/
SELECT CONVERT(VARCHAR(10),@DateTime ,108) AS Date

/*For mm-dd-yyyy format*/
SELECT CONVERT(VARCHAR(10),@DateTime ,110) AS Date

/*For yyyy/mm/dd format*/
SELECT CONVERT(VARCHAR(10),@DateTime ,111) AS Date

/*For yyyymmdd format*/
SELECT CONVERT(VARCHAR(10),@DateTime ,112) AS Date

Temporary Fix for The Below Error

0
Msg 1033, Level 15, State 1, Line 6
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.


Fix 1:

select '0','All',1 RN
union all
select *,ROW_NUMBER() over(order by Name) RN from (select '0' SNo,'Aa' Name
union all
select '0','Ab'
union all
select '0','A'
union all
select '0','Albama'
union all

select '0','Antartica')A order by RN


Fix 2:

  select '0','All' Last_Name
  union all

 select * from (select  top 100000000   * from
 ( select Source_Id,Last_Name from iasdata.dim_agent )a
 order by Last_Name asc)a


--
- Ashif Ahamed . A



Indexing NULL table column values for fast SQL performance

0
 

Indexing NULL table column values for fast SQL performance


Note: Starting in Oracle 11g, there is new "create index" syntax that allows NULL values to be included in the index:

create index
    emp_ename_idx
on
   emp 
   (ename asc, 1)
;

Here, the "1" tells Oracle that to index on NULL values within the tables.


One problem with pre 11g databases (see above) is having the optional ability to index on a NULL column.  By default, relational databases ignore NULL values (because the relational model says that NULL means "not present").  Hence, Oracle indexes will not include NULL values. 

For example, this index definition would not index on "open positions", new employee positions that are stored with a NULL employee name:

create index
    emp_ename_idx
on
   emp 
   (ename)
;

Whenever a SQL query asks for the open position employee slots "where ename is NULL", there will be no index entries for NULLS in emp_name_idx and Oracle would perform an unnecessary large-table full-table scan.

Execution Plan
---------------------------------------------------------
0 SELECT STATEMENT Optimizer=CHOOSE (Cost=1 Card=1 Bytes=6) 
1 0 TABLE ACCESS (FULL) OF 'EMP' (Cost=1 Card=1 Bytes=6)

To get around the optimization of SQL queries that choose NULL column values, we can create a function-based index using the null value built-in SQL function to index only on the NULL columns. 

Note that the "null value" (NVL) function replaces NULL values with the character string "null', a real value that can participate in an index:

 
-- create an FBI on ename column with NULL values
create index
    emp_null_ename_idx
on
   emp 
   (nvl(ename,'null'));
 
analyze index emp_null_ename_idx compute statistics;
 
You can also do this techniques with NULL numeric values.  This syntax replaces NULL values with a zero:
 
-- create an FBI on emp_nbr column with NULL values
create index
    emp_null_emp_nbr_idx
on
   emp 
   (nvl(ename,o));
 
analyze index emp_null_ename_idx compute statistics;

Now we can use the index and greatly improve the speed of any queries that require access to the NULL columns.  Note that we must make one of two changes:

    1- Add a hint to force the index

   2 - Change the WHERE predicate to match the function

Here is an example of using an index on NULL column values:

-- insert a NULL row
insert into emp (empno) values (999);

set autotrace traceonly explain;

-- test the index access (change predicate to use FBI)
select /*+ index(emp_null_ename_idx) */
   ename
from
   emp e
where
   nvl(ename,'null') = 'null'
;

SQL Server SP Call With Out Parameter

0

Returning stored procedure parameter values to a calling stored procedure in SQL SERVER

 

Overview

In a previous topic we discussed how to pass parameters into a stored procedure, but another option is to pass parameter values back out from a stored procedure.  One option for this may be that you call another stored procedure that does not return any data, but returns parameter values to be used by the calling stored procedure.

Explanation

Setting up output paramters for a stored procedure is basically the same as setting up input parameters, the only difference is that you use the OUTPUT clause after the parameter name to specify that it should return a value.  The output clause can be specified by either using the keyword "OUTPUT" or just "OUT".

Simple Output

CREATE PROCEDURE uspGetAddressCount @City nvarchar(30), @AddressCount int OUTPUT

AS

SELECT @AddressCount = count(*)

FROM AdventureWorks.Person.Address

WHERE City = @City

Or it can be done this way:

CREATE PROCEDURE uspGetAddressCount @City nvarchar(30), @AddressCount int OUT

AS

SELECT @AddressCount = count(*)

FROM AdventureWorks.Person.Address

WHERE City = @City

To call this stored procedure we would execute it as follows.  First we are going to declare a variable, execute the stored procedure and then select the returned valued.

DECLARE @AddressCount int

EXEC uspGetAddressCount @City = 'Calgary', @AddressCount = @AddressCount OUTPUT

SELECT @AddressCount

This can also be done as follows, where the stored procedure parameter names are not passed.

DECLARE @AddressCount int

EXEC uspGetAddressCount 'Calgary', @AddressCount OUTPUT

SELECT @AddressCount

Oracle TRUNC function

0

Let's look at some Oracle TRUNC function examples and explore how to use the TRUNC function in Oracle/PLSQL.

For example:

TRUNC(TO_DATE('22-AUG-03'), 'YEAR')  Result: '01-JAN-03'    TRUNC(TO_DATE('22-AUG-03'), 'Q')  Result: '01-JUL-03'    TRUNC(TO_DATE('22-AUG-03'), 'MONTH')  Result: '01-AUG-03'    TRUNC(TO_DATE('22-AUG-03'), 'DDD')  Result: '22-AUG-03'    TRUNC(TO_DATE('22-AUG-03'), 'DAY')  Result: '17-AUG-03'

SQL SERVER – Find Last Day of Any Month – Current Previous Next

0

SQL SERVER – Find Last Day of Any Month – Current Previous Next

Few questions are always popular. They keep on coming up through email, comments or from co-workers. Finding Last Day of Any Month is similar question. I have received it many times and I enjoy answering it as well.

I have answered this question twice before here:

SQL SERVER – Script/Function to Find Last Day of Month
SQL SERVER – Query to Find First and Last Day of Current Month

Today, we will see the same solution again. Please use the method you find appropriate to your requirement.

Following script demonstrates the script to find last day of previous, current and next month.
----Last Day of Previous Month
SELECT DATEADD(s,-1,DATEADD(mmDATEDIFF(m,0,GETDATE()),0))
LastDay_PreviousMonth
----Last Day of Current Month
SELECT DATEADD(s,-1,DATEADD(mmDATEDIFF(m,0,GETDATE())+1,0))
LastDay_CurrentMonth
----Last Day of Next Month
SELECT DATEADD(s,-1,DATEADD(mmDATEDIFF(m,0,GETDATE())+2,0))
LastDay_NextMonth

ResultSet:
LastDay_PreviousMonth
———————–
2007-07-31 23:59:59.000

LastDay_CurrentMonth
———————–
2007-08-31 23:59:59.000

LastDay_NextMonth
———————–
2007-09-30 23:59:59.000

If you want to find last day of month of any day specified use following script.
--Last Day of Any Month and Year
DECLARE @dtDate DATETIME
SET @dtDate '8/18/2007'
SELECT DATEADD(s,-1,DATEADD(mmDATEDIFF(m,0,@dtDate)+1,0))
LastDay_AnyMonth

ResultSet:
LastDay_AnyMonth
———————–
2007-08-31 23:59:59.000