import pandas as pd
from sqlalchemy.engine import create_engine
from sqlalchemy.engine import URL
from sqlalchemy.types import String, Date, DateTime
from sqlalchemy import text
import sqlalchemy as sa
import pyodbc
import oracledb
import math
table_name = 'payment__c'
conntarget = oracledb.connect(
user="HR",
password="**",
dsn="192.168.178.6/orcl")
cursortarget = conntarget.cursor()
zoek_query = "select count(table_name) from user_tables where lower(table_name)=lower('" + table_name + "')"
print(zoek_query)
cursortarget.execute(zoek_query)
if cursortarget.fetchone()[0] > 0:
cursortarget.execute("drop table " + table_name )
connection_string = "DRIVER={ODBC Driver 17 for SQL Server};SERVER=DESKTOP-8J58OIP;DATABASE=Speel;UID=sa;**"
connection_url = URL.create("mssql+pyodbc", query={"odbc_connect": connection_string})
engine = create_engine(connection_url)
with engine.begin() as conn:
df = pd.read_sql_query(sa.text("SELECT * FROM Rapportage." + table_name), conn)
sql_script = 'CREATE TABLE ' + table_name + ' (' \
+ '"ID" CLOB NULL, ' \
+ '"Person_ID__c" CLOB NULL, ' \
+ '"Indication_Processed__c" CLOB NULL, ' \
+ '"CreatedById" CLOB NULL, ' \
+ '"LastModifiedById" CLOB NULL, ' \
+ '"CreatedDate" CLOB NULL, ' \
+ '"LastModifiedDate" CLOB NULL, ' \
+ '"Provider_ID__c" CLOB NULL ' \
+ ')'
print(sql_script)
#query = text(sql_script)
# Execute the SQL script
cursortarget.execute(sql_script)
df.info()
row_count = len(df)
nmbr_cycles = math.floor(row_count / 100000) + 1
print('aantal cycles ' + str(nmbr_cycles))
for index, row in df.iterrows():
cursortarget.execute('INSERT INTO ' + table_name + '("ID", "Person_ID__c", "Indication_Processed__c", "CreatedById", "LastModifiedById", "CreatedDate", "LastModifiedDate", "Provider_ID__c") VALUES (:1, :2, :3, :4, :5, :6, :7, :8)', tuple(row))
# Commit changes to Oracle database
if index % 100000 == 0:
print(str(index) + ' Rijen gelezen')
if index % 1000 == 0:
conntarget.commit()
conntarget.commit()
cursortarget.close()
print('*******Prog geeindigd*******')
Blog
-
Alternative way to read data from SQL server
-
Use Python to transport data
An alternative to a previous post is the programme below. This uses Pandas dataframe to transport data.
import pandas as pd from sqlalchemy.engine import create_engine from sqlalchemy.engine import URL from sqlalchemy.types import String, Date, DateTime from sqlalchemy import text import sqlalchemy as sa import pyodbc import oracledb table_name = 'migrated_pension_accrual__c' conntarget = oracledb.connect( user="HR", password="AAaa11!!", dsn="192.168.178.6/orcl") cursortarget = conntarget.cursor() zoek_query = "select count(table_name) from user_tables where lower(table_name)=lower('" + table_name + "')" print(zoek_query) cursortarget.execute(zoek_query) if cursortarget.fetchone()[0] > 0: cursortarget.execute("drop table " + table_name ) connection_string = "DRIVER={ODBC Driver 17 for SQL Server};SERVER=DESKTOP-8J58OIP;DATABASE=Speel;UID=sa;PWD=AAaa11!!" connection_url = URL.create("mssql+pyodbc", query={"odbc_connect": connection_string}) engine = create_engine(connection_url) with engine.begin() as conn: df = pd.read_sql_query(sa.text("SELECT * FROM Rapportage." + table_name), conn) sql_script = 'CREATE TABLE ' + table_name + ' (' \ + '"index" NUMBER(19,0), ' \ + '"Id" CLOB NULL, ' \ + '"Accrued_OP65__c" NUMBER NULL, ' \ + '"Accrued_OP67_VPL__c" NUMBER NULL, ' \ + '"Accrued_OP67__c" NUMBER NULL, ' \ + '"Accrued_PP65__c" NUMBER NULL, ' \ + '"Accrued_PP67_VPL__c" NUMBER NULL, ' \ + '"Accrued_PP67__c" NUMBER NULL, ' \ + '"Accrued_WzP65__c" NUMBER NULL, ' \ + '"Accrued_WzP67__c" NUMBER NULL, ' \ + '"ANW__c" NUMBER NULL, ' \ + '"Base_parttime_percentage__c" CLOB NULL, ' \ + '"CAP__c" NUMBER NULL, ' \ + '"COP65__c" NUMBER NULL, ' \ + '"COP67__c" NUMBER NULL, ' \ + '"Employer_ID__c" CLOB NULL, ' \ + '"Number_IKV__c" CLOB NULL, ' \ + '"OP67exc__c" NUMBER NULL, ' \ + '"OOP__c" NUMBER NULL, ' \ + '"Pension_base_disability__c" CLOB NULL, ' \ + '"Pension_scheme_ID__c" CLOB NULL, ' \ + '"Person_ID__c" NUMBER NULL, ' \ + '"PP67exc__c" NUMBER NULL, ' \ + '"PP67Risk__c" NUMBER NULL, ' \ + '"PREP_age__c" NUMBER NULL, ' \ + '"PREP__c" NUMBER NULL, ' \ + '"Provider_ID__c" NUMBER NULL, ' \ + '"Reason_of_change__c" CLOB NULL, ' \ + '"Registration_date__c" DATE NULL, ' \ + '"Send_date_to_core__c" DATE NULL, ' \ + '"Sequence_number_employment__c" CLOB NULL, ' \ + '"Sequence_number_part__c" NUMBER NULL, ' \ + '"Savings_amount__c" NUMBER NULL, ' \ + '"Version_number_migrated__c" NUMBER NULL, ' \ + '"WZP67exc__c" NUMBER NULL, ' \ + '"WZPRisk__c" NUMBER NULL, ' \ + '"Type_of_VPL__c" CLOB NULL, ' \ + '"Pension_base_continuation__c" CLOB NULL, ' \ + '"Value_PP67_Risc_base__c" NUMBER NULL, ' \ + '"CreatedById" CLOB NULL, ' \ + '"CreatedDate" CLOB NULL, ' \ + '"LastModifiedById" CLOB NULL, ' \ + '"LastModifiedDate" CLOB NULL ' \ + ')' print(sql_script) #query = text(sql_script) # Execute the SQL script cursortarget.execute(sql_script) cursortarget.close() DIALECT = 'oracle' SQL_DRIVER = 'cx_oracle' USERNAME = 'hr' PASSWORD = 'AAaa11!!' HOST = '192.168.178.6' PORT = 1521 SERVICE = 'orcl' ENGINE_PATH_WIN_AUTH = DIALECT + '+' + SQL_DRIVER + '://' + USERNAME + ':' + PASSWORD +'@' + HOST + ':' + str(PORT) + '/?service_name=' + SERVICE print(ENGINE_PATH_WIN_AUTH) engine = create_engine(ENGINE_PATH_WIN_AUTH, echo=False) df.info() row_count = len(df) nmbr_cycles = math.floor(row_count / 100000) + 1 print('aantal cycles ' + str(nmbr_cycles)) for i in range(0,nmbr_cycles): rijtje = df.iloc[i * 100000:(i + 1 ) * 100000, 0:len(df.columns)] print('cyclus ' + str(i)) # print(rijtje.iloc[:2,]) rijtje.to_sql(name=table_name, con=engine, if_exists='append', schema='HR') -
Met Python van SQL Server naar Oracle
Plse find enclosed a script to write records from SQL Server to Oracle:
import pyodbc import datetime conn = pyodbc.connect('DSN=SQLServer;UID=sa;PWD=**') conntarget = pyodbc.connect('DSN=Rekendoos;UID=hr;PWD=**') table_name = 'MIGRATED_DIVORCE_SETTLEMENT__C' cursor = conn.cursor() cursortarget = conntarget.cursor() cursor.execute('select * from Rapportage.' + tabel) columns = [column[0] for column in cursor.description] kolommen = '' for x in range(len(columns) - 1): kolommen = kolommen + columns[x] + ', ' kolommen = kolommen + columns[len(columns) - 1] results = [columns] + [row for row in cursor.fetchall()] zoek_query = "select count(table_name) from user_tables where lower(table_name)=lower('" + table_name + "')" cursortarget.execute(zoek_query) if cursortarget.fetchone()[0]== 1: cursortarget.execute("drop table " + table_name ) stmt = 'CREATE TABLE "HR"."MIGRATED_DIVORCE_SETTLEMENT__C" ' \ + '( "ID" CLOB, ' \ + ' "BPP65_AMOUNT__C" NUMBER,' \ + ' "BPP67_AMOUNT__C" NUMBER, ' \ + ' "BPP67_VPL_AMOUNT__C" NUMBER, ' \ + ' "END_DATE_SETTLEMENT_PERIOD__C" DATE, ' \ + ' "PENSION_SCHEME_ID__C" CLOB, ' \ + ' "PERSON_ID_1__C" CLOB, ' \ + ' "PERSON_ID_2__C" CLOB, ' \ + ' "PROVIDER_ID__C" CLOB, ' \ + ' "REGISTRATION_DATE__C" DATE, ' \ + ' "SEND_DATE_TO_CORE__C" DATE, ' \ + ' "SETTLEMENT_DATE__C" DATE, ' \ + ' "START_DATE_RELATIONSHIP__C" DATE,' \ + ' "START_DATE_SETTLEMENT__C" CLOB,' \ + ' "VERSION_NUMBER_SETTLEMENT__C" CLOB, ' \ + ' "VOP65_AMOUNT__C" NUMBER, ' \ + ' "VOP67_AMOUNT__C" NUMBER, ' \ + ' "VOP67_VPL_AMOUNT__C" NUMBER,' \ + ' "VPREP__C" NUMBER, ' \ + ' "VOPHOOG__C" NUMBER, ' \ + ' "VTOP_TOT_AOW__C" NUMBER, ' \ + ' "CREATEDBYID" CLOB, ' \ + ' "CREATEDDATE" CLOB, ' \ + ' "LASTMODIFIEDBYID" CLOB, ' \ + ' "LASTMODIFIEDDATE" CLOB' \ + ' ) ' cursortarget.execute(stmt) for i in range(1,len(results)): Sql_insert_query1 = "INSERT INTO " + table_name + " (" + kolommen + ") VALUES (" Sql_insert_query2 = '' for j in range(len(columns)): uitkomst = results[i][j] if isinstance(uitkomst, str): uitkomst = uitkomst.replace("'"," ") uitkomst = "\'" + uitkomst + "\'" if uitkomst is None: uitkomst = '' uitkomst = "\'" + uitkomst + "\'" if isinstance(uitkomst, (int, float)): uitkomst = str(uitkomst) if isinstance(uitkomst, (datetime.date, datetime.datetime) ): # print(str(j) + 'date') uitkomst = str(uitkomst) uitkomst = uitkomst[0:10] uitkomst = "to_date('" + uitkomst + "','yyyy-mm-dd')" Sql_insert_query2 = Sql_insert_query2 + uitkomst if j < int(len(columns)) - 1: Sql_insert_query2 = Sql_insert_query2 + ", " Sql_insert_queryn = ")" Sql_insert_query = Sql_insert_query1+Sql_insert_query2+Sql_insert_queryn if i % 1000 == 0: print(str(i) + ' Rijen gelezen') conntarget.commit() # print(Sql_insert_query) cursortarget.execute(Sql_insert_query) conntarget.commit() print('Lezen gereed') cursor.close() conntarget.close()Here, the results are written to a list.
-
Where is a record that creates an error
It might be that you see one record in a view that generates an error somewhere but you have not clue which record might generate that error. It could then be that the next logic helps. Create this procedure:
create or replace package mypkg_tom as cursor c is select * from tpl_v_calc_dossier; type cur_tab is table of c%rowtype; function foo return mypkg_tom.cur_tab pipelined; end;
which is followed by the package definition:
create or replace package body mypkg_tom as function foo return mypkg_tom.cur_tab pipelined as l_data cur_tab; begin open c; fetch c bulk collect into l_data; close c; dbms_output.put_line('omvang '||l_data.count); for i in 1..l_data.count loop pipe row( l_data(i) ); if mod(i, 1000) < 1 then dbms_output.put_line('regel '||i); end if; if (i between 250000 and 250010) then dbms_output.put_line(i); end if; end loop; return ; end; end;It can then be called by something like select count(*) from table( mypkg_tom.foo ); This then shows a counter at each 1000th record. You then know where the error may lie. Next step is to precisely locate the error and solve the issue.
An alternative is to show the ids from the view:
create or replace package mypkg_tom
as
cursor c_varchar is select id from tpl_v_calc_dossier;
type cur_varchar is table of varchar(216);
function foo_varchar return mypkg_tom.cur_varchar pipelined;
end;followed by
create or replace package body mypkg_tom
as
function foo_varchar return mypkg_tom.cur_varchar pipelined
as
l_data cur_varchar;
opvang varchar(216);
begin
open c_varchar;
fetch c_varchar bulk collect into l_data;
close c_varchar;
dbms_output.put_line('omvang '||l_data.count);
for i in 1..l_data.count
loop
pipe row( l_data(i) );
if mod(i, 1000) < 1 then dbms_output.put_line('regel '||i); end if;
opvang := l_data(i);
if (i between 250000 and 250010) then dbms_output.put_line(opvang); end if;
end loop;
return ;
end;
end;which can then be called as select count(*) from table( mypkg_tom.foo_varchar );
-
Closing records
In a data warehouse environment, we may have to close records when we have new records that are added to the system. Let me first provide the sql.
CASE mut.etl_valid_from
WHEN MAX(mut.etl_valid_from) OVER
(PARTITION BY TO_NUMBER(mut.company_code||mut.gl_account_nr))
THEN mut.etl_valid_to
ELSE LEAD(mut.etl_valid_from) OVER
(PARTITION BY TO_NUMBER(mut.company_code||mut.gl_account_nr)
ORDER BY mut.etl_valid_from)
ENDThis is a really nice concise text. Let me show a few items. With the CASE clause, the records are selected that have a maximum for the timestamp when records are entered. The dataset is split according to company code and the gl_account_nr. So for each combination of company code and the gl_account_nr, the maximum of etl_validated_from is calculated. When the etl_valid_from is equal to the maximum, a provided etl_valid_to is inserted into the data base. When etl_valid_from has a lower value, the data from a leading record is taken. That value is the etl_valid_from a leading record that stems from the same bracket of company code and the gl_account_nr that is ordered on etl_valid_from.
-
Partitions in Oracle
Oracle has the concept of partitions: the idea that a set of records is stored in one partition, that is directly accessible. This avoids the situation that large segments of data must be investigated before a record is found.
The code to generate such table is:
CREATE TABLE "HR"."FCT_BLN_ALLOC_USAGE" ( "PROCESSING_DATE_SK" NUMBER, "INCREMENT_OFFSET_SEC" NUMBER, "ETL_REFRESH_DATE" DATE, "USG_ID" VARCHAR2(50 CHAR), "BLN_ID" VARCHAR2(50 CHAR), "ALN_ID" VARCHAR2(50 CHAR), "SOURCE_SYSTEM_ID" VARCHAR2(3 CHAR) ) PARTITION BY RANGE ("PROCESSING_DATE_SK") INTERVAL (1) (PARTITION "P_FIRST" VALUES LESS THAN (1)) ;Based on the values that we enter for PROCESSING_DATE_SK, the record is positioned in one partition or another.
We can derive the partition names from next query:SELECT partition_name FROM dba_tab_partitions WHERE table_name = 'FCT_BLN_ALLOC_USAGE';
The partition names can then be used in a sql that derives the records from a certain partitiopn:
select * from FCT_BLN_ALLOC_USAGE partition (SYS_P2932)
However, such action requires two steps:
- Retrieve the partition names (which is often not allowed)
- Use the partition name in a sql statement.
A more step is to retrieve the records in one statement. This looks like:
SELECT *
FROM FCT_BLN_ALLOC_USAGE PARTITION FOR (2); -
Calculate elapse period in Teradata
A nice feature of a DBMS is to be able to calculate elapse period. Important questions like “how many days to go to pension?’, can be addressed. In teradata, this looks like:
select cast(1231125 as date) - current_date;
This little sentence involves a typecasting from an integer to a date. The integer is 1221125 that stands for 1900+123 = 2023 as the year in which pension will start, 11 as the month and 25 as the day. So cast(1231125) leads to 25 November, 2023. The current date is now. The difference is the number of days before retirement. In this case 766 days.
-
A pivot table in Teradata
Teradata recently introduced the concept of pivoting in its sql. The idea is relatively straightforward. A column is selected that has some distinct values. Pivoting then implies that the distinct values are translated into columns. Doing so another value is used to derive the actual content in the columns. This can be a sum, maximum or any other aggregate.
Let us start with a table. Its content is:

Let us use yr as the column that is pivoted. It has 2010 and 2011 as distinct values. We will have “2010” and “2011” as new columns. These columns are loaded with aggregates that are derived from another column, sales.
Let us look at the code:
SELECT "2010" as sales_2010, "2011" as sales_2011
FROM (select yr, sales from s1)s1
PIVOT (SUM(sales) FOR yr IN (2010,2011)) tmp;Notice that we use an inline query as the source. This inline query only contains yr and sales. Column yr is translated into two columns: 2010 and 2011. The end result will be one row with two two columns. The values in the row will be an aggregate (=sum) on sales.
So, we get:

We can also retain an extra column from the original table. Let us retain “mon”. The code then gets:
SELECT mon, "2010" as sales_2010, "2011" as sales_2011 FROM (select yr, mon, sales from s1)s1 PIVOT (SUM(sales) FOR yr IN (2010,2011)) tmp;
And the result is:

-
Using the SAS Viya environment
Today, I played with the new SAS Viya environment. This environment has been promoted as a cloud based environment by SAS that acts as a SAAS solution to analytics needs from an organisation. This implies that we only need an internet connection and a browser to access this environment.
How does it work. A small example might show you the working.
We may upload an Excel file to this environment with:
FILENAME REFFILE FILESRVC FOLDERPATH='/Users/tom.van.maanen@capgemini.com/My Folder' FILENAME='invoer.xlsx';
PROC IMPORT DATAFILE=REFFILE
DBMS=XLSX
OUT=WORK.NAMEN;
GETNAMES=YES;
RUN;
data test;
set namen;
run;This imports a file (= invoer.xlsx) into the traditional SAS work library. The file was imported from a local computer into the cloud environment. This cloud environment is made visible in the Viya Cloud environment with:

We then uploaded this file into work.namen. It can be seen in the library:

We then start a CAS session. This stands for Cloud Analytic Service. Next code takes care of this. Subsequently, I assign the CAS session as a library.
cas mysession sessopts=(caslib=casuser timeout=1000 locale="en_US"); caslib _all_ list; caslib _all_ assign; proc casutil; list tables; run;
The result is that I can see libraries that are connected to the CAS session:

I then copy the work.names dataset into a CAS library with:
proc casutil;
load data = work.test outcaslib = "casuser"
casout = "mytest" promote ;
run;It is now stored as dataset in the CAS library and it may be used in a session. We may write a script like:
data casuser.mytest2; set casuser.mytest end=eof; select; when (leeftijd > 50) klas = 'oud '; when (leeftijd <= 50) klas = 'jonkie '; otherwise klas = 'onbekend '; end; if eof then put _N_; run; proc print data = casuser.mytest2;run; PROC SGPLOT DATA = casuser.mytest2; VBAR klas; RUN;
which generates:

-
A graceful way to end a SAS job
I found one possibility to gracefully end a SAS job. The code is rather straight forward. One opens a macro with a condition statement %if %then etc. If the condition is fulfilled, the code may run as previously anticipated. If not, a return statement ends processing the procedure.
%let dsn=work.a; %macro abortIfRemaining; %if (%sysfunc(exist(&dsn))) %then %do; --insert data step statements %end; %else %do; %put &dsn not found; %return; %end; %mend abortIfRemaining; %abortIfRemaining;