A challenging dynamic SQL query problem
hi All,
I have a very interesting problem at work:
We have this particular table defined as follows :
CREATE TABLE sales_data (
sales_id NUMBER,
sales_m01 NUMBER,
sales_m02 NUMBER,
sales_m03 NUMBER,
sales_m04 NUMBER,
sales_m05 NUMBER,
sales_m06 NUMBER,
sales_m07 NUMBER,
sales_m08 NUMBER,
sales_m09 NUMBER,
sales_m10 NUMBER,
sales_m11 NUMBER,
sales_m12 NUMBER,
sales_prior_yr NUMBER );
The columns 'sales_m01 ..... sales_m12' represents aggregated monthly sales, in which 'sales_m01' translates to 'sales for the month of january, january being the first month, 'sales_m02' sales for the month of february, and so on.
The problem I face is that we have a project which requires that a parameter be passed to a stored procedure which stands for the month number which is then used to build a SQL query with the following required field aggregations, which depends on the parameter passed :
Sample 1 : parameter input: 4
Dynamically-built SQL query should be :
SELECT
SUM(sales_m04) as CURRENT_SALES,
SUM(sales_m01+sales_m02+sales_m03+sales_m04) SALES_YTD
FROM
sales_data
WHERE
sales_id = '0599768';
Sample 2 : parameter input: 8
Dynamically-built SQL query should be :
SELECT
SUM(sales_m08) as CURRENT_SALES,
SUM(sales_m01+sales_m02+sales_m03+sales_m04+
sales_m05+sales_m06+sales_m07+sales_m08) SALES_YTD
FROM
sales_data
WHERE
sales_id = '0599768';
So in a sense, the contents of SUM(sales_m01 ....n) would vary depending on the parameter passed, which should be a number between 1 .. 12 which corresponds to a month, which in turn corresponds to an actual field range on the table itself. The resulting dynamic query should only aggregate those columns/fields in the table which falls within the range given by the input parameter and disregards all the remaining columns/fields.
Any solution is greatly appreciated.
Thanks.
Hi another simpler approach is using decode
try like this
SQL> CREATE TABLE sales_data (
2 sales_id NUMBER,
3 sales_m01 NUMBER,
4 sales_m02 NUMBER,
5 sales_m03 NUMBER,
6 sales_m04 NUMBER,
7 sales_m05 NUMBER,
8 sales_m06 NUMBER,
9 sales_m07 NUMBER,
10 sales_m08 NUMBER,
11 sales_m09 NUMBER,
12 sales_m10 NUMBER,
13 sales_m11 NUMBER,
14 sales_m12 NUMBER,
15 sales_prior_yr NUMBER );
Table created.
SQL> select * from sales_data;
SALES_ID SALES_M01 SALES_M02 SALES_M03 SALES_M04 SALES_M05 SALES_M06 SALES_M07 SALES_M08 SALES_M09 SALES_M10 SALES_M11 SALES_M12 SALES_PRIOR_YR
1 124 123 145 146 124 126 178 189 456 235 234 789 19878
2 124 123 145 146 124 126 178 189 456 235 234 789 19878
1 100 200 300 400 500 150 250 350 450 550 600 700 10000
1 101 201 301 401 501 151 251 351 451 551 601 701 10000----now for your requirement. see below query if there is some problem then tell.
SQL> SELECT sum(sales_m&input_data), DECODE (&input_data,
2 1, SUM (sales_m01),
3 2, SUM (sales_m01 + sales_m02),
4 3, SUM (sales_m01 + sales_m02 + sales_m03),
5 4, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04),
6 5, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04 + sales_m05),
7 6, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06),
8 7, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07),
9 8, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08),
10 9, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08+sales_m09),
11 10,SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08+sales_m09+sales_m10),
12 11,SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08+sales_m09+sales_m10+sales_m11),
13 12,SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08+sales_m09+sales_m10+sales_m11+sales_m12)
14 ) total
15 FROM sales_data
16 WHERE sales_id = 1;
Enter value for input_data: 08
Enter value for input_data: 08
old 1: SELECT sum(sales_m&input_data), DECODE (&input_data,
new 1: SELECT sum(sales_m08), DECODE (08,
SUM(SALES_M08) TOTAL
890 5663
Similar Messages
-
Best way to spool DYNAMIC SQL query to file from PL/SQL
Best way to spool DYNAMIC SQL query to file from PL/SQL [Package], not SqlPlus
I'm looking for suggestions on how to create an output file (fixed width and comma delimited) from a SELECT that is dynamically built. Basically, I've got some tables that are used to define the SELECT and to describe the output format. For instance, one table has the SELECT while another is used to defined the column "formats" (e.g., Column Order, Justification, FormatMask, Default value, min length, ...). The user has an app that they can use to customize the output...which leaving the gathering of the data untouched. I'm trying to keep this formatting and/or default logic out of the actual query. This lead me into a problem.
Example query :
SELECT CONTRACT_ID,PV_ID,START_DATE
FROM CONTRACT
WHERE CONTRACT_ID = <<value>>Customization Table:
CONTRACT_ID : 2,Numeric,Right
PV_ID : 1,Numeric,Mask(0000)
START_DATE : 3,Date,Mask(mm/dd/yyyy)The first value is the kicker (ColumnOrder) as well as the fact that the number of columns is dynamic. Technically, if I could use SqlPlus...then I could just use SPOOL. However, I'm not.
So basically, I'm trying to build a generic routine that can take a SQL string execute the SELECT and map the output using data from another table to a file.
Any suggestions?
Thanks,
JasonYou could build the select statement within PL/SQL and open it using a cursor variable. You could write it to a file using the package 'UTL_FILE'. If you want to display the output using SQL*Plus, you could have an out parameter as a ref cursor.
-
SSRS - Stored procedure with Dynamic SQL Query
Am calling stored procedure in SSRS report. I have used Dynamic SQL query in stored procedure as I don't know the column name and column count. And I have used like below at end of the stored procedure "select * from ##temptable".
As I have used dynamic column, am not able to create report with this stored procedure. Can someone help me out to resolve this issue.
It will be highly appreciated if I get help.
ThanksI have tried everything. But nothing has worked out.
If I get solution for below issue, it would be highly appreciated.
"An error occurred during local report processing.
The definition of the repport 'Main Report' is invalid.
The report defintion is not valid. Details: The report definition has an invalid target namespace 'http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition' which cannot be upgraded.
Thanks
Hello,
I would suggest you post the complete error message to us for further investigation, if you preview the report before you deploy you may get a more detailed error that will help diagnose the source of the problem.
This issue is more related to SQL Server Reporting Services, it's more appropriate to discuss it in the forum below:
https://social.technet.microsoft.com/Forums/sqlserver/en-US/home?forum=sqlreportingservices
Don't forget to elaborate your issue with more detail.
For the manual column, it might be the calculated field in SSRS. Here is the article for your reference, please see:
http://technet.microsoft.com/en-us/library/dd239322(v=sql.110).aspx
Regards,
Elvis Long
TechNet Community Support -
Build dynamic SQL query in Database Adapter.
Hi All,
I have a requirement to build dynamic sql query at Database Adapter.
My BPEL process is getting search spec as input from siebel. I need to process this searchspec in BPEL and need to build the SQL query dynamically at Database Adapter to fetch the records from DB.
it goes like this....
1. Sieble Search Spec: city1 OR city2 OR city3 OR city4 .....
I need to build query as
select * from S_ADDR_PER where city like 'city1' OR city like 'city2' OR city like 'city3' OR city like 'city4' ......
2. Siebel Search spec: city1 AND country1 AND state1....
I need to build query as
Select * from S_ADDR_PER where city like 'city1' AND country like 'country1' AND state like 'state1' ....
3. Siebel Search spec: state
I need to build query as
select * from S_ADDR_PER where state like '%state%';
Is it feasible in Database Adapter? if its Yes.
Any guidelines to achieve this?
Thank you
ChandraHi All,
I have a requirement to build dynamic sql query at Database Adapter.
My BPEL process is getting search spec as input from siebel. I need to process this searchspec in BPEL and need to build the SQL query dynamically at Database Adapter to fetch the records from DB.
it goes like this....
1. Sieble Search Spec: city1 OR city2 OR city3 OR city4 .....
I need to build query as
select * from S_ADDR_PER where city like 'city1' OR city like 'city2' OR city like 'city3' OR city like 'city4' ......
2. Siebel Search spec: city1 AND country1 AND state1....
I need to build query as
Select * from S_ADDR_PER where city like 'city1' AND country like 'country1' AND state like 'state1' ....
3. Siebel Search spec: state
I need to build query as
select * from S_ADDR_PER where state like '%state%';
Is it feasible in Database Adapter? if its Yes.
Any guidelines to achieve this?
Thank you
Chandra -
Flash chart with dynamic sql query does not display
Hi,
In my schema SIVOA I have a lot of tables declared like this :
CREATE TABLE "SIVOA"."EVV_xxxx"
( "CLEF_VAR" NUMBER(4,0),
"DATE1" DATE,
"VALEUR" NUMBER(16,8) Only the last part of the name changes "xxxx". For example E009, E019, etc....
I am making a chart page with report and want the user to select a name of a table and I will display using dynamic sql query, the table report and chart.
P184_ENAME is a select list returning the last part of the name of the table, fro example 'E009', 'E019', etc.
P8_CLEF_VAR is an item containing a value. This value is a key retrieved like this :SELECT CLEF_VAR
FROM SIVOA.SITE_ECHELLE
WHERE SITE = :P184_ENAMEI built a classic report using a sql dynamic function :DECLARE
x VARCHAR2 (4000);
BEGIN
x := 'SELECT NULL, DATE1, VALEUR FROM SIVOA.EVV_'
|| UPPER(:p184_ename)
|| ' WHERE CLEF_VAR = :p8_clef_var' ;
RETURN (x);
END;:p8_clef_var is an itme containing the value '4544'.
This works perfectly fine !
When I use this sql fucytion into a flash chart it does not work. I get this message "No data found".
I do not understand why a the report get a result and not the chart !
But if i hard-code the number of the CLEF_VAR instead of fetching it from :p8_clef_var I get a nice chart ! Go figure !DECLARE
x VARCHAR2 (4000);
BEGIN
x := 'SELECT NULL, DATE1, VALEUR FROM SIVOA.EVV_'
|| UPPER(:p184_ename)
|| ' WHERE CLEF_VAR = 4544 ' ;
RETURN (x);
I cannot stay with the key (CLEF_VAR) hard-coded unformtunately !
My question is how to get the chart displaying properly ??
Thank you for your kind answers.
ChristianAlex,
Using your request, with the classic report I get results (data), but I get the same message with the Flash chart : "No data found" ! I don't know how to investigate this. i tried many things but nothing works.
Christian
PS I tried this :
DECLARE
X VARCHAR2 (4000);
BEGIN
x := 'SELECT NULL, DATE1, ROUND(VALEUR,2) FROM SIVOA.EVV_'
|| UPPER (:p184_ename) ||
' WHERE CLEF_VAR = '
|| :p8_clef_var ||
' AND DATE1 BETWEEN TO_DATE ('''
||:P8_DATE_DEBUT||''', ''DD/MM/YYYY HH24:MI'') AND TO_DATE ('''
||:P8_DATE_FIN||''', ''DD/MM/YYYY HH24:MI'')'
RETURN (X);
END; But it does not work either. I could find that the SLQ syntax generated is good becaus I put it into an item which display the return done by the pls/sql.
What is sttange also with the classic report is that if I do click on next or previous to see another rows, I get the message "No data found". If I try to export the report I get an excel file with "No data fouid".
Does anybody already tried my "need" here ? i find strange thant I should not be the firs one trying to get a report an tables which name would be "dynamic".
Tahnk you.
Edited by: Christian from France on Feb 13, 2009 3:05 AM -
Build stored procedure from a dynamic SQL query
I have the following method, that receives a string from a textbox and creates a dynamic select command. Since I am using a dataSet I cannot execute a dynamic SQL query by calling a method of a strongly-typed dataset (.xsd). I have been told that the best
way to do this is to pass an array of values to the stored procedure.
But I have no clue how to build the stored procedure.
string[] allWords = txtSearch.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string sql = "SELECT Books.ISBN, Books.Title, Books.Tag, Books.Image, Books.photoType, Publishers.Name AS publisherName FROM Books INNER JOIN Publishers ON Books.codPublisher = Publishers.codPublisher WHERE ";
using (SqlCommand command = new SqlCommand())
for (int i = 0; i < allWords.Length; ++i)
if (i > 0)
sql += "OR ";
string paramName = "@param" + i.ToString();
sql += string.Format("(Books.Title LIKE {0}) ", paramName);
command.Parameters.AddWithValue(paramName, allWords[i] + "%");
command.CommandText = sql;
//execute the SQL query against the db...After hours around this, I have came with this solution.
private SqlConnection sqlConn = new SqlConnection();
private System.Data.DataSet dataSet = new System.Data.DataSet();
private System.Data.DataTable dataTable;
private System.Data.DataRow dataRow;
private SqlCommand search(string searchParam, int searchOption)
SqlCommand command = new SqlCommand();
string sql;
string[] allWords = searchParam.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (searchOption == 1)
sql = "SELECT Livros.ISBN, Livros.Titulo, Livros.Tema, Livros.Resumo, Livros.Imagem, Livros.fotoTipo, Editoras.Nome AS nomeEditora FROM Livros INNER JOIN Editoras ON Livros.codEditora = Editoras.codEditora WHERE ";
else
sql = "SELECT Livros.ISBN, Livros.Titulo, Livros.Tema, Livros.Resumo, Livros.Imagem, Livros.fotoTipo, Editoras.Nome AS nomeEditora FROM Livros INNER JOIN livrosAutores ON Livros.ISBN = livrosAutores.ISBN INNER JOIN Autores ON livrosAutores.idAutor = Autores.idAutor INNER JOIN Editoras ON Livros.codEditora = Editoras.codEditora WHERE ";
using (command)
for (int i = 0; i < allWords.Length; ++i)
if (i > 0)
sql += "OR ";
if (searchOption == 1)
sql += string.Format("(Livros.Titulo LIKE '%{0}%') ", allWords[i]);
else
sql += string.Format("(Livros.Autor LIKE '%{0}%') ", allWords[i]);
command.CommandText = sql;
return command;
protected void Bind()
sqlConn.ConnectionString = Properties.Settings.Default.BibliotecaConnectionString;
string connectionString = sqlConn.ConnectionString.ToString();
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(search(searchText, searchOption).CommandText, connectionString);
sqlDataAdapter.Fill(dataSet, "livrosTitulo");
dataTable = dataSet.Tables["livrosTitulo"];
dataGrid.DataContext = dataTable.DefaultView; -
Proxy to JDBC scenario need dynamic sql query for sender .
Hi Experts,
I am developing proxy to jdbc scenario. in this i need to pass dynamic sql query whre we are passing classical method like below.
while we are passing select stmt in constant and mapped with access field and key field mapped with key field.
MY requirement is like instead of passing select stmt in constant where i can generate dynamically and passed in one field and mapped with access field.Hi Ravinder,
A simple UDF or use of graphical mapping functions in most cases should provide you everything you need to construct a dynamic SQL statement for your requirement.
Regards,
Ryan Crosby -
Need generic dynamic sql query to generate nodes depending on dealer levels
Input table:
create table #test(dealerid integer ,dealerlvl integer)
insert into #test values(1,1)
insert into #test values(1,2)
insert into #test values(1,3)
insert into #test values(1,4)
insert into #test values(2,1)
insert into #test values(2,2)
insert into #test values(2,3)
insert into #test values(2,4)
insert into #test values(2,5)
insert into #test values(2,6)
go
create table #test2(dealerid integer,node integer,prntnode integer,dealerlvl integer)
insert into #test2 values (1,234,124,2)
insert into #test2 values (1,123,234,1)
insert into #test2 values (1,238,123,2)
insert into #test2 values (1,235,238,3)
insert into #test2 values (1,253,235,4)
insert into #test2 values (2,21674,124,3)
insert into #test2 values (2,1233,21674,1)
insert into #test2 values (2,2144,1233,2)
insert into #test2 values (2,2354,2144,3)
insert into #test2 values (2,24353,2354,4)
insert into #test2 values (2,245213,24353,5)
insert into #test2 values (2,2213,245213,6)
Expected result :
I have two test case here with dealerID1 and dealerID 2
Result for DealerID1
Result needed for DealerID2:
the levels for dealers might change (Dealer1 has 4 levels, and Dealer 2 has 6 levels) so i need to create an dynamic sql query which lists each node as separate columns depending on the levels.
I have hacked the query to give the result I need
select a.dealerid,a.node as Lvl1,b.node as lvl2,c.node as lvl3,d.node as lvl4
from #test2 a
join #test2 b on a.node=b.prntnode
join #test2 c on b.node=c.prntnode
join #test2 d on c.node=d.prntnode
where a.dealerid=1 and a.dealerlvl=2
select a.dealerid,a.node asLvl1,
b.node as lvl2,c.node as lvl3,d.node as lvl4,e.node as lvl5,f.node as lvl6--,a.dealerlvl,a.dealerid
from #test2 a
join #test2 b on a.node=b.prntnode
join #test2 c on b.node=c.prntnode
join #test2 d on c.node=d.prntnode
join #test2 e on d.node=e.prntnode
join #test2 f on e.node=f.prntnode
where a.dealerid=2 and a.dealerlvl=3
I am sure there is a better way to do this with dynamic sql. please help.
Thanks-- Dynamic PIVOT
DECLARE @T AS TABLE(y INT NOT NULL PRIMARY KEY);
DECLARE
@cols AS NVARCHAR(MAX),
@y AS INT,
@sql AS NVARCHAR(MAX);
-- Construct the column list for the IN clause
SET @cols = STUFF(
(SELECT N',' + QUOTENAME(y) AS [text()]
FROM (SELECT DISTINCT dealerlvl AS y FROM dbo.test2) AS Y
ORDER BY y
FOR XML PATH('')),
1, 1, N'');
-- Construct the full T-SQL statement
-- and execute dynamically
SET @sql = N'SELECT *
FROM (SELECT dealerid, dealerlvl, node
FROM dbo.Test2) AS D
PIVOT(MAX(node) FOR dealerlvl IN(' + @cols + N')) AS P;';
EXEC sp_executesql @sql;
GO -
NVARCHAR (MAX) TO PRINT DYNAMIC SQL QUERY TO A SQL FILE
Hi
I have a requirement where i need to write an SP which would construct a huge query using dynamic SQL and save the Dynamic query to a file.
The Dynamic SQL Variable I am using as @NVARCHAR(MAX) but since the query being built is large (>4000 characters), I am not able to select it into a table. PRINT @SQL prints the whole query but SELECT @SQL prints only upto 4000 characterrs.
And I need to save this huge dynamix sql to a file using the SP.
Any thoughts as to how i can achieve this?
RajivThis is a know problem with dynamic SQL nvarchar(max) concatenation.
See below for correct assembly of large SQL strings:
CREATE table #temp(qry nvarchar(max));
declare @cmd nvarchar(max);
SELECT @cmd=CONCAT(CONVERT(nvarchar(max),N'SELECT '),
CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
CONVERT(nvarchar(max),N'FROM SYS.TABLES'));
insert into #temp SELECT @cmd;
select * from #temp;
select len(qry), datalength(qry) from #temp;
-- 16022 32044
drop table #temp;
Dynamic SQL: http://www.sqlusa.com/bestpractices/dynamicsql/
Kalman Toth Database & OLAP Architect
SQL Server 2014 Design & Programming
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012 -
SQL query problem - select max (case... aggregate function)
Hi,
I have a problem with below sql query, it gives me problem/error message 'ORA-00937: not a single-group group function', why?
select sag.afdeling, sag.sagsnr, to_char(sag.start_dato, 'yyyy-mm-dd'), sag.stat, BOGF_TRANS.TRANSTYPE,
max (case when BOGF_TRANS.TRANSTYPE = 'K' then sum(bogf_trans.belobdkk) end) + -- as "TRANSTYPE K",
max (case when BOGF_TRANS.TRANSTYPE = 'D' then sum(bogf_trans.belobdkk) end) as "TRANSTYPE K & D",
max (case when BOGF_TRANS.TRANSTYPE = 'S' then sum(bogf_trans.belobdkk) end) as "SUM TRANSTYPE S"
from sag
join bogf_trans on sag.selskab = bogf_trans.selskab and sag.sagsnr = bogf_trans.sagsnr and sag.afdeling = bogf_trans.afdeling
where SAG.SELSKAB=37 and SAG.AFDELING = 'SUS' AND SAG.SAGSNR = 10876
group by sag.afdeling, sag.sagsnr, sag.start_dato, sag.stat, BOGF_TRANS.TRANSTYPE
If I exclude (columns) as below it give me correct summations (max (case... sum(...)) but then I miss some important info that I need
select
max (case when BOGF_TRANS.TRANSTYPE = 'K' then sum(bogf_trans.belobdkk) end) + -- as "TRANSTYPE K",
max (case when BOGF_TRANS.TRANSTYPE = 'D' then sum(bogf_trans.belobdkk) end) as "TRANSTYPE K & D",
max (case when BOGF_TRANS.TRANSTYPE = 'S' then sum(bogf_trans.belobdkk) end) as "SUM TRANSTYPE S"
from sag
join bogf_trans on sag.selskab = bogf_trans.selskab and sag.sagsnr = bogf_trans.sagsnr and sag.afdeling = bogf_trans.afdeling
where SAG.SELSKAB=37 and SAG.AFDELING = 'SUS' AND SAG.SAGSNR = 10876
group by sag.afdeling, sag.sagsnr, sag.start_dato, sag.stat, BOGF_TRANS.TRANSTYPE
Any ideas?Moved to more sutable forum, sorry.
-
Dynamic SQL Query to Find Special Characters in Table columns
Hi,
I am new to OTN FORUMS.
I am trying to find the columnsi of a table which have special characters in them.
I am planning on using this query
select ' select INSTR('||column_name||', chr(0))
from '||table_name||'where INSTR('||column_name||', chr(0)) >0' from user_tab_columns
where table_name='Account'
and spool the output to run as a script.
Is this the right way or do u suggest any modifications to the query?
Thanks in advance.Hi,
I think your basic approach is right. Since you can't hard-code the table- or column names into the query, you'll need dynamic SQL.
Instead SQL-from-SQL (that is, writing a pure SQL query, whose output is SQL code), you could do the whole job in PL/SQL, but I don't see any huge advantage either way.
When you say "Special character<b>s</b>", do you really mean "one given special character" (in this case, CHR(0))?
Will you ever want to search for multiple special characters at once?
What if table foo has a column bar, and in 1000 rows of foo, bar contains CHR (0). Do you want 1000 rows of output, each showing the exact position of the first CHR(0)? If the purpose is to look at theese rows later, shouldn't you include the primary key in the output? What if CHR(0) occurs 2 or more times in the same string?
If you'd rather have one row of output, that simply says that the column foo.bar sometimes contains a CHR(0), then you could do something like this:
SELECT 'foo', 'bar'
FROM dual
WHERE EXISTS (
SELECT NULL
FROM foo
WHERE INSTR ( bar
, CHR (0)
) > 0
); -
Hi,
I need to retieve the number of records that will be retrieved by a query as follows.
How can this be done?
Is there a method to do it using native dynamic sql (open .. for .. using ) instead of DBMS_SQL (Because Native is faster than dbms_SQL )?
The following block demostrates what I need to do where v_query will hold the query text.
declare
v_query varchar2(32000);
v_count number;
begin
select query_text into v_query from groups_table where id =1;
dbms_output.put_line('count = '||v_count);
end;
Thanks in AdvanceIs there a way to use sql%rowcount to do something similar?
Afraid not
I mean if there is a way to get better performance in case of very large query. Like for example in oracle forms, when using Query --> count records it retrieves the nubmer of records that will be fetched.
I think you'll find forms simply does a select count(*) from the base table (adding and predicates where necessary).
What are you going to use it for? Maybe there is an alternative route you can take... -
Difference between Static SQL Query and Dynamic SQL Query.
Hi,
Please explain the basic difference between static and dynamic sql queries. Please explain with example.Static: http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10472/static.htm
Dynamic: http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10472/dynamic.htm -
PL/SQL function body returning SQL Query Problem
I have wandered around the forums and found quite a bit of helpful information that has gotten me to the point I am now at. Unfortuntely, PL/SQL is not my strongest point and I am getting an error when I attempt to run my report.
This is what I have for my package:
CREATE OR REPLACE PACKAGE LIB2.report_query
is
function create_report2(v1 IN varchar2) RETURN VARCHAR2;
end report_query;
CREATE OR REPLACE PACKAGE BODY LIB2.report_query
as
function create_report2(v1 in varchar2) return varchar2
is
l_vc_format HTMLDB_APPLICATION_GLOBAL.VC_ARR2 := HTMLDB_UTIL.STRING_TO_TABLE(v1);
l_format varchar2(255) := HTMLDB_UTIL.TABLE_TO_STRING(l_vc_format);
q1 varchar2(32767) := ' ';
begin
q1 :=
'select b.BOOK_ID, bk.book_id bkid, bkk.book_id bkkid, b.TITLE, b.SUBTITLE, b.SERIES, b.VOLUME, b.ISBN, f.FORMAT_RET, b.DESCRIPTION, .PUBLISHED,'
||'b.PURCHASED_FROM, b.COMMENTS, b.WEBSITE, c.LENGTH_MINS, stragg(p.last_name || '', '' || p.first_name) Author, '
||'stragg(p.person_id) person_id, '
||'pb.name PUBLISHER, decode(b.abridged, ''Y'',''Abridged'',''N'',''Unabridged'') Abridged,'
||'(nvl(d.disk01,0)+nvl(d.disk02,0)+nvl(d.disk03,0)+nvl(d.disk04,0)+nvl(d.disk05,0)+nvl(d.disk06,0)+nvl(d.disk07,0)+nvl(d.disk08,0)+'
||'nvl(d.disk09,0)+nvl(d.disk10,0)+nvl(d.disk11,0)+nvl(d.disk12,0)+nvl(d.disk13,0)+nvl(d.disk14,0)+nvl(d.disk15,0)+nvl(d.disk16,0)+nvl(d.disk17,0)+'
||'nvl(d.disk18,0)+nvl(d.disk19,0)+nvl(d.disk20,0)+nvl(d.disk21,0)+nvl(d.disk22,0)+nvl(d.disk23,0)+nvl(d.disk24,0)+nvl(d.disk25,0)+nvl(d.disk26,0)+'
||'nvl(d.disk27,0)+nvl(d.disk28,0)+nvl(d.disk29,0)+nvl(d.disk30,0)+nvl(d.disk31,0)+nvl(d.disk32,0)+nvl(d.disk33,0)+nvl(d.disk34,0)+nvl(d.disk35,0)+'
||'nvl(d.disk36,0)+nvl(d.disk37,0)+nvl(d.disk38,0)+nvl(d.disk39,0)+nvl(d.disk40,0)+nvl(d.disk41,0)+nvl(d.disk42,0)+nvl(d.disk43,0)+nvl(d.disk44,0)+'
||'nvl(d.disk45,0)+nvl(d.disk46,0)+nvl(d.disk47,0)+nvl(d.disk48,0)+nvl(d.disk49,0)+nvl(d.disk50,0)) total_tracks'
||'from book b, '
||'book bk,'
||'book bkk,'
||'person p,'
||'lkup_book_author la,'
||'lkup_book_publisher lp,'
||'lkup_book_format lkf,'
||'format f,'
||'publisher pb,'
||'conversion_info_audio c,'
||'lkup_book_disk_info d'
||'where b.book_id = la.book_id'
||'and b.book_id = bk.book_id'
||'and b.book_id = bkk.book_id'
||'and p.person_id = la.author_id'
||'and b.book_id = lp.book_id'
||'and b.book_id = c.book_id'
||'and b.book_id = d.book_id'
||'and b.book_id = lkf.book_id'
||'and lkf.format_id = f.format_id'
||'and pb.publisher_id(+) = lp.publisher_id'
||'and b.wishlist = ''N'''
||'and (upper(b.book_id) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.title) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.subtitle) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.series) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.volume) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.isbn) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.format) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.description) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.published) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.purchased_from) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.comments) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(b.website) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(p.last_name) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(p.first_name) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(pb.name) like ''%'' || upper(:P40_SEARCH) || ''%'''
||'or upper(:P40_SEARCH) is null)'
||'and ((upper(b.title) like ''%'' || upper(:P40_TITLE) || ''%'' or upper(:P40_TITLE) is null))'
||'and ((upper(b.series) like ''%'' || upper(:P40_SERIES) || ''%'' or upper(:P40_SERIES) is null))'
||'and ((upper(p.last_name) like ''%'' || upper(:P40_LASTNAME) || ''%'' or upper(:P40_LASTNAME) is null))'
||'and ((upper(p.first_name) like ''%'' || upper(:P40_FIRSTNAME) || ''%'' or upper(:P40_FIRSTNAME) is null))'
||'and ((upper(f.format_ret) in (upper(l_vc_format)) or upper(:P40_FORMAT) is null))'
||'group by b.BOOK_ID, bk.book_id, bkk.book_id, b.TITLE, b.SUBTITLE, b.SERIES, b.VOLUME, b.ISBN, f.FORMAT_ret, b.DESCRIPTION, '
||'b.PUBLISHED, b.PURCHASED_FROM, b.COMMENTS, b.WEBSITE, c.LENGTH_MINS, pb.name, b.abridged, '
||'(nvl(d.disk01,0)+nvl(d.disk02,0)+nvl(d.disk03,0)+nvl(d.disk04,0)+nvl(d.disk05,0)+nvl(d.disk06,0)+nvl(d.disk07,0)+nvl(d.disk08,0)+'
||'nvl(d.disk09,0)+nvl(d.disk10,0)+nvl(d.disk11,0)+nvl(d.disk12,0)+nvl(d.disk13,0)+nvl(d.disk14,0)+nvl(d.disk15,0)+nvl(d.disk16,0)+nvl(d.disk17,0)+'
||'nvl(d.disk18,0)+nvl(d.disk19,0)+nvl(d.disk20,0)+nvl(d.disk21,0)+nvl(d.disk22,0)+nvl(d.disk23,0)+nvl(d.disk24,0)+nvl(d.disk25,0)+nvl(d.disk26,0)+'
||'nvl(d.disk27,0)+nvl(d.disk28,0)+nvl(d.disk29,0)+nvl(d.disk30,0)+nvl(d.disk31,0)+nvl(d.disk32,0)+nvl(d.disk33,0)+nvl(d.disk34,0)+nvl(d.disk35,0)+'
||'nvl(d.disk36,0)+nvl(d.disk37,0)+nvl(d.disk38,0)+nvl(d.disk39,0)+nvl(d.disk40,0)+nvl(d.disk41,0)+nvl(d.disk42,0)+nvl(d.disk43,0)+nvl(d.disk44,0)+'
||'nvl(d.disk45,0)+nvl(d.disk46,0)+nvl(d.disk47,0)+nvl(d.disk48,0)+nvl(d.disk49,0)+nvl(d.disk50,0))';
RETURN q1;
EXCEPTION
WHEN OTHERS THEN
RETURN q1;
end create_report2;
end;
And here is what I have for my Region Source on my report:
return lib2.report_query.create_report2(v('P40_FORMAT'));
Here is my error when I run the page:
failed to parse SQL query:
ORA-00936: missing expression
I have tried the region source line in many variations, this is just my latest one. None of them have worked. I am quite obviously missing something quite important and probably extremely silly. Any ideas?
Thanks!
ChrissyChrissy,
This is what the package returns as a query:
select b.BOOK_ID, bk.book_id bkid, bkk.book_id bkkid,
b.TITLE, b.SUBTITLE, b.SERIES, b.VOLUME, b.ISBN, f.FORMAT_RET,
b.DESCRIPTION, .PUBLISHED,b.PURCHASED_FROM, b.COMMENTS, b.WEBSITE,
c.LENGTH_MINS, stragg(p.last_name || ', ' || p.first_name) Author,
stragg(p.person_id) person_id, pb.name PUBLISHER, decode(b.abridged,
'Y','Abridged','N','Unabridged') Abridged,
(nvl(d.disk01,0)+nvl(d.disk02,0)+nvl(d.disk03,0)+nvl(d.disk04,0)+nvl(d.disk05,0)
nvl(d.disk06,0)nvl(d.disk07,0)+nvl(d.disk08,0)+nvl(d.disk09,0)+nvl(d.disk10,0)
nvl(d.disk11,0)nvl(d.disk12,0)+nvl(d.disk13,0)+nvl(d.disk14,0)+nvl(d.disk15,0)
nvl(d.disk16,0)nvl(d.disk17,0)+nvl(d.disk18,0)+nvl(d.disk19,0)+nvl(d.disk20,0)
nvl(d.disk21,0)nvl(d.disk22,0)+nvl(d.disk23,0)+nvl(d.disk24,0)+nvl(d.disk25,0)
nvl(d.disk26,0)nvl(d.disk27,0)+nvl(d.disk28,0)+nvl(d.disk29,0)+nvl(d.disk30,0)
nvl(d.disk31,0)nvl(d.disk32,0)+nvl(d.disk33,0)+nvl(d.disk34,0)+nvl(d.disk35,0)
nvl(d.disk36,0)nvl(d.disk37,0)+nvl(d.disk38,0)+nvl(d.disk39,0)+nvl(d.disk40,0)
nvl(d.disk41,0)nvl(d.disk42,0)+nvl(d.disk43,0)+nvl(d.disk44,0)+nvl(d.disk45,0)
nvl(d.disk46,0)nvl(d.disk47,0)+nvl(d.disk48,0)+nvl(d.disk49,0)+nvl(d.disk50,0)) total_tracksfrom book b,
book bk,book bkk,person p,lkup_book_author la,lkup_book_publisher lp,
lkup_book_format lkf,format f,publisher pb,conversion_info_audio c,
lkup_book_disk_info dwhere b.book_id = la.book_idand b.book_id = bk.book_idand b.book_id = bkk.book_idand p.person_id = la.author_idand
b.book_id = lp.book_idand b.book_id = c.book_idand b.book_id = d.book_idand
b.book_id = lkf.book_idand lkf.format_id = f.format_idand pb.publisher_id(+) = lp.publisher_idand
b.wishlist = 'N'and (upper(b.book_id) like '%' || upper(:P40_SEARCH) || '%'
or upper(b.title) like '%' || upper(:P40_SEARCH) || '%'or upper(b.subtitle) like '%' ||
upper(:P40_SEARCH) || '%'or upper(b.series) like '%' || upper(:P40_SEARCH) || '%'or
upper(b.volume) like '%' || upper(:P40_SEARCH) || '%'or upper(b.isbn) like '%' ||
upper(:P40_SEARCH) || '%'or upper(b.format) like '%' || upper(:P40_SEARCH) || '%'or upper(b.description) like '%' || upper(:P40_SEARCH) || '%'or upper(b.published)
like '%' || upper(:P40_SEARCH) || '%'or upper(b.purchased_from) like '%' ||
upper(:P40_SEARCH) || '%'or upper(b.comments) like '%' || upper(:P40_SEARCH)
|| '%'or upper(b.website) like '%' || upper(:P40_SEARCH) || '%'or
upper(p.last_name) like '%' || upper(:P40_SEARCH) || '%'or upper(p.first_name)
like '%' || upper(:P40_SEARCH) || '%'or upper(pb.name) like '%' ||
upper(:P40_SEARCH) || '%'or upper(:P40_SEARCH) is null)and
((upper(b.title) like '%' || upper(:P40_TITLE) || '%' or
upper(:P40_TITLE) is null))and ((upper(b.series) like '%' ||
upper(:P40_SERIES) || '%' or upper(:P40_SERIES) is null))and
((upper(p.last_name) like '%' || upper(:P40_LASTNAME) || '%' or
upper(:P40_LASTNAME) is null))and ((upper(p.first_name) like '%' ||
upper(:P40_FIRSTNAME) || '%' or upper(:P40_FIRSTNAME) is null))and
((upper(f.format_ret) in (upper(l_vc_format)) or upper(:P40_FORMAT) is null))
group by b.BOOK_ID, bk.book_id, bkk.book_id, b.TITLE, b.SUBTITLE, b.SERIES, b.VOLUME,
b.ISBN, f.FORMAT_ret, b.DESCRIPTION, b.PUBLISHED, b.PURCHASED_FROM, b.COMMENTS, b.WEBSITE,
c.LENGTH_MINS, pb.name, b.abridged, (nvl(d.disk01,0)+nvl(d.disk02,0)+nvl(d.disk03,0)
nvl(d.disk04,0)nvl(d.disk05,0)+nvl(d.disk06,0)+nvl(d.disk07,0)+nvl(d.disk08,0)
nvl(d.disk09,0)nvl(d.disk10,0)+nvl(d.disk11,0)+nvl(d.disk12,0)+nvl(d.disk13,0)
nvl(d.disk14,0)nvl(d.disk15,0)+nvl(d.disk16,0)+nvl(d.disk17,0)+nvl(d.disk18,0)
nvl(d.disk19,0)nvl(d.disk20,0)+nvl(d.disk21,0)+nvl(d.disk22,0)+nvl(d.disk23,0)
nvl(d.disk24,0)nvl(d.disk25,0)+nvl(d.disk26,0)+nvl(d.disk27,0)+nvl(d.disk28,0)
nvl(d.disk29,0)nvl(d.disk30,0)+nvl(d.disk31,0)+nvl(d.disk32,0)+nvl(d.disk33,0)
nvl(d.disk34,0)nvl(d.disk35,0)+nvl(d.disk36,0)+nvl(d.disk37,0)+nvl(d.disk38,0)
nvl(d.disk39,0)nvl(d.disk40,0)+nvl(d.disk41,0)+nvl(d.disk42,0)+nvl(d.disk43,0)
nvl(d.disk44,0)nvl(d.disk45,0)+nvl(d.disk46,0)+nvl(d.disk47,0)+nvl(d.disk48,0)
nvl(d.disk49,0)nvl(d.disk50,0))
This query will never work. I marked only couple of errors you have there. Actually,
I meant "formating" errors rather than "syntactical" errors. You are missing spaces
all over the place. This is why I suggested to use a CLOB column in a test table
to return the query for debugging purposes - this is how I do it at least, when I need
to escape and concatenate a lot of code.
If you are referencing item values from a user session in a function or a procedure,
then you need to use the v('ITEM') syntax instead of :ITEM syntax. However, if the
output of this procedure will be used as a function returning SQL query, you will
be fine with :ITEM.
Denes Kubicek
http://deneskubicek.blogspot.com/
http://htmldb.oracle.com/pls/otn/f?p=31517:1
------------------------------------------------------------------- -
Hi,
I have a search form with 1 field (date picker) - the user chooses a date and a report based on a sql query is shown.
I want the report to be based on only the month and year, and not the particular day.
If there is a date picker (or something similar) for only month and/or year, then I can change my form, but I don't see this option.
So, I'm trying to write my query to ignore the Day portion in the search form and just do a search based on the month and year, but i'm having trouble with this.
This is my query...
select d.dept, count(e.emp_id) "No. of Employees"
from dept d, employees e
where e.date_created = trunc(:P13_DATE, 'MONTH YYYY')
and d.dept_id = e.dept_id
group by dept
order by dept
How do I write the where clause so that the search is done only on month and year?
Or otherwise, how can I change the search form to exclude the day from the date?
Thanks.Hi,
Oh, the invalid number is the result of :P13_DATE being a string value. all item values are actually strings (or varchar2 if you like) when you referencing them with ':Px_ITEM' format. With the pl/sql function there are 2 possible ways to reference item, namely the function: V('Px_ITEM') and NV('Px_ITEM'). Although in SQL varchar2 => number conversion can be dealed with by the SQL engine.
Unfortunally there is no pl/sql method for getting a DATE of an date-picker item (based on its format mask etc.). Patrick Wolf has added this function in his ApExLib framework, function DV. I find this a nice extension.
Maybe you are looking for
-
Failed boot after (apparently) successful SSD installation
Tried to replace the main hard drive of my wife's 13 inch MacBook with an SSD restored from a Time Machine backup. Everything seemed to go smoothly, but the machine won't boot, it just keeps showing "You need to restart your computer." Ran disk utili
-
Hi, this computer works fine with Ubuntu (10.10, Unity makes it a dog ), unusably slow with Vista, and who knows about Win7. If you have successfully added more RAM than the 2gigs which supposedly is the max, let me know how it went. 4 gigs would mak
-
IMac Won't Auto Connect To Internet Via Ethernet Cable
I'm Using An iMac OSX Leopard, And When I Turn On My Computer The Internet Isn't Connected Even Though It Works. I Get Server Not Found In Safari And Firefox. I Have To Unplug The Ethernet Cable And Plug It Back In For It To Work, But If I Turn Off T
-
So in AS2 to add button functionality to a movie clip, you'd type: myButton_mc.onPress=function(){ gotoAndPlay("something"); How is this accomplished in AS3 WITHOUT using external .as files, classes, etc? It seems like all the tutorials/books I read,
-
How do I stop a device from accessing my iCloud information?
I no longer want a particular device to display any of my iCloud files, etc. For example, I want to remove browser settings (bookmarks, etc.) from a work computer I will no longer be using. Also, currently, if I open some iWork programs or Text Edit,