How to write this query compatible with oracle database - sql

I am facing issue to convert the sql query to oracle .Actually i am new to oracle db.
SELECT TI1.FOLDERRSN, DBO.F_OPENTAX_PROPERTYROLL_FOLDER(TI1.FOLDERRSN) ROLL,
TI1.DUEDATE DUEDATE, TI1.YEARFORBILLING,(TI1.SUMDUETAX + TI1.SUMPAIDTAX + TI1.SUMDUEPENALTY + TI1.SUMPAIDPENALTY) OUTSTANDING
FROM TAXINSTALLMENT TI1 WHERE (TI1.SUMDUETAX + TI1.SUMPAIDTAX + TI1.SUMDUEPENALTY + TI1.SUMPAIDPENALTY) > 0
AND EXISTS (SELECT * FROM TAXINSTALLMENT TI2 WHERE YEAR(TI2.DUEDATE) BETWEEN 1980 AND YEAR(GETDATE()) - 5 AND (TI2.SUMDUETAX + TI2.SUMPAIDTAX + TI2.SUMDUEPENALTY + TI2.SUMPAIDPENALTY) > 0
AND TI2.FOLDERRSN = TI1.FOLDERRSN ) ORDER BY TI1.FOLDERRSN, DUEDATE DESC
Anyone give me idea to change to oracle .
Thanks

The statement uses a function F_OPENTAX_PROPERTYROLL_FOLDER(TI1.FOLDERRSN) in Schema DBO. Make sure you have installed that function in that database Schema and have granted an execution right to the user in question or to PUBLIC for that matter.
EDIT: Moreover there is no function YEAR in Oracle. You must replace it with EXTRACT: EXTRACT(YEAR FROM TI2.DUEDATE) and for GetDate(): EXTRACT(YEAR FROM SYSDATE).

Related

How can I check the maximum value from a set of tables in SQL Server (if possible)?

We have a set of databases (80 in total). Every single one has a table called tblProfessions. The tables are not standardized. For example:
EDIT: all the databases are on the same server.
The DB1.dbo.tblProfessions is like:
intProfessionCode
strProfessionDescription
1
lawyer
2
dentist
...
...
30
doctor
And the DB72.dbo.tblProfessions is as follows:
intProfessionCode
strProfessionDescription
1
designer
2
butcher
...
...
80
chef
Suppose I ran a script from DBO1 to DBO72, and I found that the biggest table has 80 entries (in this case the DBO72 is the biggest one).
By my limited knowledge, all I know is to run the below script database by database, and write it down in a spreadsheet manually:
SELECT MAX(intProfessionCode) FROM [DB].dbo.tblProfessions;
Is there a script to run and loop through all the tblProfessions and get the one with the most entries? All I want is the biggest number found.
Thanks in advance.
You should be able to do something like this:
WITH dat
AS
(
SELECT 'db1' AS database_name, MAX(intProfessionCode) AS max_intProfessionCode
FROM DB1.dbo.tblProfessions
UNION ALL
...
UNION ALL
SELECT 'db72' AS database_name, MAX(intProfessionCode) AS max_intProfessionCode
FROM DB72.dbo.tblProfessions
)
SELECT dat.db, dat.max_intProfessionCode
FROM dat
INNER JOIN (SELECT MAX(max_intProfessionCode) AS max_intProfessionCode_overall
FROM dat) y
ON dat.max_intProfessionCode = y.max_intProfessionCode_overall
For situations like this, I usually query the catalog to write the above script rather than typing it out:
WITH
dat AS
(
SELECT STRING_AGG('SELECT ''' + QUOTENAME(s.name) + ''' AS db,
MAX(intProfessionCode) AS max_intProfessionCode
FROM ' + QUOTENAME(s.name) + '.' + QUOTENAME('dbo') + '.' + QUOTENAME('tblProfessions') + '
UNION ALL',' ') AS s
FROM sys.databases s
WHERE s.name LIKE 'DB%' --EDIT APPROPRIATELY
)
SELECT 'WITH dat
AS
(' + SUBSTRING(s,1,LEN(s) - LEN(' UNION ALL')) + ')
SELECT dat.db, dat.max_intProfessionCode
FROM dat
INNER JOIN (SELECT MAX(max_intProfessionCode) AS max_intProfessionCode_overall
FROM dat) y
ON dat.max_intProfessionCode = y.max_intProfessionCode_overall' AS scrpt
FROM dat;
Make sure the above is only returning data for the appropriate databases by editing the WHERE clause in the CTE, then copy the output, paste elsewhere and run it to get your results.

ADF -pass SQL query in source with single quotes in date column

I am trying to pass parameters in dynamic pipeline in source query inside data flow. Tablename and Column name is dynamic and will be passed through parameters. But i got an error while executing the below ADF query:
ADF Query: concat('SELECT ', $ValidationColumn, ' FROM ', $ValidationTable,' WHERE audit_datetime >= ', replace($StartAuditDateTime,'T',''),' AND audit_datetime <= ' ,replace($EndAuditDateTime,'T','') )
Expected SQL query: Select ID from Master where audit_datetime >= '2020-07-23 18:47:20.5666' AND audit_datetime <= '2020-07-24 01:47:20.5456'
Please try below expression to form your query in your ADF Mapping dataflow expression builder.
"SELECT '{$ValidationColumn}' FROM '{$ValidationTable}' WHERE audit_datetime >= '{$StartAuditDateTime}' AND audit_datetime <= '{$EndAuditDateTime}'"
This will result in below QUERY formation:
SELECT ID FROM Master WHERE audit_datetime >= '2020-07-23 18:47:20.5666' AND audit_datetime <= '2020-07-24 01:47:20.5456'
I am assuming you want to escape single quote to get '{yourDateValue}' format,
you can do that like this ''''
example:
#{concat('select * from [yourtable] WHERE [yourColumn] >=','''',{yourexpression},'''')}
Use this SQL syntax in Expression builder in ADF Data Flow where you need to use singe quotes
"SELECT * FROM myTable WHERE someColumn = 'Y'"

Creating Dynamic Dates as Variable (Column Names) in SQL

First, I have read about similar posts and have read the comments that this isn't an ideal solution and I get it but the boss (ie client) wants it this way. The parameters are as follows (for various reasons too bizarre to go into but trust me):
1. SQL Server Mgmt Studio 2016
2. NO parameters or pass throughs or temp tables. All has to be within contained code.
So here we go:
I need to create column headings that reflect dates:
1. Current date
2. Most recent quarter end prior to current date
3. Most recent quarter end prior to #2
4. Most recent quarter end prior to #3
5. Most recent quarter end prior to #4
6. Most recent quarter end prior to #5
So if using today's date, my column names would be as follows
12/18/2016 9/30/2016 6/30/2016 3/31/2016 12/31/2016 9/30/2015
I can easily do it in SAS but can't in SQL given the requirements stated above.
Help please with same code.
Thank you
Paula
Seems like a long way to go for something which really belongs in the presentation layer. That said, consider the following:
Let's assume you maintain a naming convention for your calculated fields, for example [CurrentDay], [QtrMinus1], [QtrMinus2], [QtrMinus3], [QtrMinus4],[QtrMinus5]. Then we can wrap your complicated query in some dynamic SQL.
Just as an illustration, let's assume your current query results looks like this
After the "wrap", the results will then look like so:
The code - Since you did NOT exclude Dynamic SQL.
Declare #S varchar(max)='
Select [CustName]
,['+convert(varchar(10),GetDate(),101)+'] = [CurrentDay]
,['+Convert(varchar(10),EOMonth(DateFromParts(Year(DateAdd(QQ,-1,GetDate())),DatePart(QQ,DateAdd(QQ,-1,GetDate()))*3,1)),101)+'] = [QtrMinus1]
,['+Convert(varchar(10),EOMonth(DateFromParts(Year(DateAdd(QQ,-2,GetDate())),DatePart(QQ,DateAdd(QQ,-2,GetDate()))*3,1)),101)+'] = [QtrMinus2]
,['+Convert(varchar(10),EOMonth(DateFromParts(Year(DateAdd(QQ,-3,GetDate())),DatePart(QQ,DateAdd(QQ,-3,GetDate()))*3,1)),101)+'] = [QtrMinus3]
,['+Convert(varchar(10),EOMonth(DateFromParts(Year(DateAdd(QQ,-4,GetDate())),DatePart(QQ,DateAdd(QQ,-4,GetDate()))*3,1)),101)+'] = [QtrMinus4]
,['+Convert(varchar(10),EOMonth(DateFromParts(Year(DateAdd(QQ,-5,GetDate())),DatePart(QQ,DateAdd(QQ,-5,GetDate()))*3,1)),101)+'] = [QtrMinus5]
From (
-- Your Complicated Query --
Select * from YourTable
) A
'
Exec(#S)
If it helps the visualization, the generated SQL is as follows:
Select [CustName]
,[12/18/2016] = [CurrentDay]
,[09/30/2016] = [QtrMinus1]
,[06/30/2016] = [QtrMinus2]
,[03/31/2016] = [QtrMinus3]
,[12/31/2015] = [QtrMinus4]
,[09/30/2015] = [QtrMinus5]
From (
-- Your Complicated Query --
Select * from YourTable
) A
Here is one way using dynamic query
DECLARE #prior_quarters INT = 4,
#int INT =1,
#col_list VARCHAR(max)=Quotename(CONVERT(VARCHAR(20), Getdate(), 101))
WHILE #int <= #prior_quarters
BEGIN
SELECT #col_list += Concat(',', Quotename(CONVERT(VARCHAR(20), Eomonth(Getdate(), ( ( ( ( Month(Getdate()) - 1 ) % 3 ) + 1 ) * -1 ) * #int), 101)))
SET #int+=1
END
--SELECT #col_list -- for debugging
EXEC ('select '+#col_list+' from yourtable')

Calculate value per day

I have Oracle table where I insert data about network upload and download speed.
CREATE TABLE AGENT_HISTORY(
EVENT_DATE DATE,
NETWORK_UP NUMBER,
NETWORK_DOWN NUMBER
)
I want to generate Bar chart for last 30 days and display total upload traffic per day(24 hours).
select * from AGENT_HISTORY where EVENT_DATE >= SYSDATE - 30;
The problem which I don't know how to solve is how I can calculate the traffic for each day from the column NETWORK_UP. The result of the query should be 30 days with total upload traffic for each day. Is this possible without PL/SQL procedure?
You can do a query like this to aggregate totals data for both the network_up and network_down columns per day.
select trunc(event_day,'day') event_date
,sum(network_up) tot_network_up
,sum(network_down) tot_network_down
from agent_history
where event_day >= trunc(sysdate,'day') - interval '30' day
group by trunc(event_day,'day');
You can do it without embbeding the query in PL/SQL stored code depending on what you use for front end, in java you could you use something like this
Statement stmt = null;
String schema_name = 'abc';
String query = "select trunc(event_day,'day') event_date," +
"sum(network_up) tot_network_up," +
"sum(network_down) tot_network_down " +
"from " + schema_name +".agent_history " +
"where event_day >= trunc(sysdate,'day') " +
"- interval '30' day " +
"group by trunc(event_day,'day')"
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String event_data = rs.getString("EVENT_DATE");
int tot_network_up = rs.getInt("TOT_NETWORK_UP");
int tot_network_down= rs.getInt("TOT_NETWORK_DOWN");
.....
}
catch (SQLException e) {
.......
} finally {
......
}
With something like this you just execute pure SQL.
My guess is that you just want to aggregate the data. Something like
SELECT trunc(event_date),
sum(network_up) total_up,
sum(network_down) total_down
FROM agent_history
WHERE event_date >= trunc(sysdate) - 30
GROUP BY trunc(event_date)
If that is not what you want, it would be very helpful to post some sample data, expected output, etc.

concat apostrophe to oracle sql query

Hi all I am looking for some pointers on how I can add an apostrophe to my query results on my first column.
My current query:
set verify off
set colsep "',"
set pagesize 2000
ALTER SESSION SET NLS_DATE_FORMAT='DD-MON-YY-HH24:MI:SS';
spool /home/user/out.txt
select '[' || table1.collectdatetime as "['Date-Time",table1.cycletime as "'Time'" from table1 where interfacename='somename' and collectdatetime > (CURRENT_DATE - 1)
order by collectdatetime ASC;
Which results:
['Date-Time ','InCycleTime'
-------------------',-------------
[02-MAR-13-17:56:16', 29
What I am struglling with is getting the results to return and add an apostrophe after the [
['Date-Time ','InCycleTime'
-------------------',-------------
['02-MAR-13-17:56:16', 29
This is for an oracle 11.1.0.7 build. The data is being queried and parsed but I need to get that apostrophe issue worked out.
use this:
select '[''' || table1.collectdatetime as "['Date-Time",table1.cycletime as "'Time'" from table1 where interfacename='somename' and collectdatetime > (CURRENT_DATE - 1)
order by collectdatetime ASC;