Help with dynamic SQL
Hello,
I have the following function that works ok:
CREATE OR REPLACE FUNCTION Get_Partition_Name (sTable VARCHAR2, iImportIndex INTEGER)
RETURN VARCHAR2 IS
cursor c is select A.partition_name from (select table_name, partition_name,
extractvalue (
dbms_xmlgen.
getxmltype (
'select high_value from all_tab_partitions where table_name='''
|| table_name
|| ''' and table_owner = '''
|| table_owner
|| ''' and partition_name = '''
|| partition_name
|| ''''),
'//text()') import_value from all_tab_partitions) A where table_name = sTable and A.import_value = iImportIndex;
sPartitionName VARCHAR(20);
err_num NUMBER;
BEGIN
open c;
fetch c into sPartitionName;
IF c%ISOPEN THEN
CLOSE c;
END IF;
RETURN sPartitionName;
EXCEPTION
WHEN OTHERS THEN
err_num := SQLCODE;
--save error in log table
LOG.SAVELINE(SQLCODE, SQLERRM);
END Get_Partition_Name;
I am trying to replace the cursor statement with dynamic SQL, something like (see below) but it doesn't work any more; I think I am missing some quotes.
CREATE OR REPLACE FUNCTION Get_Partition_Name (sTable VARCHAR2, iImportIndex INTEGER)
RETURN VARCHAR2 IS
TYPE t1 IS REF CURSOR;
c t1;
sSql VARCHAR2(500);
sPartitionName VARCHAR(20);
err_num NUMBER;
BEGIN
sSql := 'select A.partition_name from (select table_name, partition_name,
extractvalue (
dbms_xmlgen.
getxmltype (
''select high_value from all_tab_partitions where table_name=''''
|| table_name
|| '''' and table_owner = ''''
|| table_owner
|| '''' and partition_name = ''''
|| partition_name
|| ''''''),
''//text()'') import_value from all_tab_partitions) A where table_name = :a and A.import_value = :b';
OPEN c FOR sSql USING sTable, iImportIndex;
fetch c into sPartitionName;
IF c%ISOPEN THEN
CLOSE c;
END IF;
RETURN sPartitionName;
EXCEPTION
WHEN OTHERS THEN
err_num := SQLCODE;
--save error in log table
LOG.SAVELINE(SQLCODE, SQLERRM);
END Get_Partition_Name;
Please advise,
Regards,
M.R.
Assuming the requirement is to find the partition in the supplied table with the supplied high value and the issue is that dba/all_tab_partitions.high_value is a long, one alternative along the same lines as you've done already is as follows. (I've just used a cursor rather than a function for simplicity of demo).
SQL> var r refcursor
SQL> set autoprint on
SQL> declare
2 ctx dbms_xmlgen.ctxhandle;
3 v_table_name VARCHAR2(40) := 'LOGMNR_USER$';
4 v_value NUMBER := 100;
5 begin
6 ctx := DBMS_XMLGEN.NEWCONTEXT
7 ('select table_name
8 , partition_name
9 , high_value hi_val
10 from dba_tab_partitions
11 where table_name = :table_name');
12 dbms_xmlgen.setbindvalue(ctx,'TABLE_NAME',v_table_name);
13 open:r for
14 with x as
15 (select xmltype(dbms_xmlgen.getxml(ctx)) myxml
16 from dual)
17 select extractvalue(x.object_value,'/ROW/TABLE_NAME') table_name
18 , extractvalue(x.object_value,'/ROW/PARTITION_NAME') partition_name
19 , extractvalue(x.object_value,'/ROW/HI_VAL') hi_val
20 from x
21 , TABLE(XMLSEQUENCE(EXTRACT(x.myxml,'/ROWSET/ROW'))) x
22 where extractvalue(x.object_value,'/ROW/HI_VAL') = v_value;
23 end;
24 /
PL/SQL procedure successfully completed.
TABLE_NAME
PARTITION_NAME
HI_VAL
LOGMNR_USER$
P_LESSTHAN100
100
SQL> I'm sure there are other ways as well. Especially with XML functionality, there's normally many ways to skin a cat.
Similar Messages
-
Help with dynamic sql across multiple tables
I have more than one similar table that stores data from different dynamically generated relations:
Following are the scripts to create and populate tables
CREATE TABLE RELATION_1(
SRC NUMBER(38, 0) NOT NULL,
TRG NUMBER(38, 0) NOT NULL,
VALUE NUMBER(38, 0) NOT NULL
CREATE TABLE RELATION_2(
SRC NUMBER(38, 0) NOT NULL,
TRG NUMBER(38, 0) NOT NULL,
VALUE NUMBER(38, 0) NOT NULL
CREATE TABLE RELATION_3(
SRC NUMBER(38, 0) NOT NULL,
TRG NUMBER(38, 0) NOT NULL,
VALUE NUMBER(38, 0) NOT NULL
insert into RELATION_1 values(1, 1, 13);
insert into RELATION_1 values(1, 2, 4);
insert into RELATION_1 values(1, 3, 6);
insert into RELATION_1 values(2, 1, 3);
insert into RELATION_1 values(2, 3, 7);
insert into RELATION_1 values(3, 1, 5);
insert into RELATION_2 values(1, 2, 1);
insert into RELATION_2 values(4, 1, 1);
insert into RELATION_2 values(5, 1, 1);
insert into RELATION_3 values(1, 1, 11);
insert into RELATION_3 values(2, 1, 4);
insert into RELATION_3 values(3, 1, 5);
insert into RELATION_3 values(1, 2, 6);
insert into RELATION_3 values(2, 2, 3);
insert into RELATION_3 values(3, 2, 5);
insert into RELATION_3 values(1, 3, 2);
insert into RELATION_3 values(2, 3, 3);
insert into RELATION_3 values(3, 3, 5);Now, I want to write a SQL that for a set of SRCs (lets say for 1,2,3) give me the top n (let's say top 10) TRGs and the SUM of all the VALUE across all the tables except for RELATION_2, i.e. RELATION_1 and RELATION 3, order by this SUM and exclude those TRGs that have entry for SRC-TRG combination in RELATION_2 table.
Thanks
Edited by: Vasif Shaikh on Sep 21, 2010 2:34 PMI didn't completely understand your requirement, but couldn't you UNION all the tables together? Then you could do your Top-n and sorting etc as if you were working with one table.
-
Selection screen - search help with dynamic sql query
hey ,
is it possible to change the search help of the selection field ?
when i create the range table i put a data element :
create a range table that consists of this new data element
LT_RANGE_TABLE = WD_THIS->M_HANDLER->CREATE_RANGE_TABLE( I_TYPENAME = 'S_CARR_ID' ).
can i control the search help via the the data element or by other methods ?
i want that when the user press F4 the values that will show is the result of a sql query that i will write .
is it possible ?
thanks
ASA.Hi,
yes it is possible...
This is my test code for say personal number select options...
lt_range_table = wd_this->m_handler->create_range_table(
i_typename = 'PERSNO' ).
add a new field to the selection
wd_this->m_handler->add_selection_field(
i_id = 'PERSNO'
I_VALUE_HELP_TYPE = if_wd_value_help_handler=>CO_PREFIX_SEARCHHELP
I_VALUE_HELP_ID = 'ZHELP_WDA_PERNR' "this is the custom search help we need to create
I_NO_INTERVALS = abap_true
it_result = lt_range_table
i_read_only = read_only ).
do the following:
1) copy the std function module: F4IF_SHLP_EXIT....to ZF4IF_SHLP_EXIT_pernr (in my case i am testing for pernr so my fm
name is like that....obviously it can be anything you want...under the recommended naming convention)
2) look for "STEP SELECT"
STEP SELECT (Select values)
3)write the code as follows:
"NOTE: this is my testing code...but you can build your logic on it....
IF CALLCONTROL-STEP = 'SELECT'.
types: begin of zpri_listing,
pernr type PERSNO,
end of zfund_listing.
DATA: lo_syuname TYPE sy-uname.
data itab type standard table of Zpri_LISTING.
data wa type zpri_listing.
DATA : t_fields LIKE TABLE OF shlp_tab-fielddescr.
DATA : w_fields LIKE LINE OF shlp_tab-fielddescr.
DATA : l_fname TYPE dfies-lfieldname.
IF lo_syuname <> sy-uname. "means we were here before and ITAB is filled...fm retains its data values...unless refresh happens
"this if condition make sure that we do not do this select all the time as long as the same user is logged in...
"a user can press f4 many times...you might want to enhance this logic a little bit more for performance
lo_syuname = sy-uname.
))))))))))))))HERE DO YOUR SELECT(((((((((((((((((((((
select pernr from "sometable" into table itab.
ENDIF.
LOOP AT shlp_tab.
LOOP AT shlp_tab-fielddescr INTO w_fields.
l_fname = w_fields-fieldname.
CALL FUNCTION 'F4UT_PARAMETER_RESULTS_PUT'
EXPORTING
parameter = w_fields-fieldname
OFF_SOURCE = 0
LEN_SOURCE = 0
VALUE =
fieldname = l_fname
TABLES
shlp_tab = shlp_tab
record_tab = record_tab
source_tab = itab
CHANGING
shlp = shlp
callcontrol = callcontrol
EXCEPTIONS
parameter_unknown = 1
OTHERS = 2
ENDLOOP.
ENDLOOP.
IF sy-subrc EQ 0.
callcontrol-step = 'DISP'.
ELSE.
callcontrol-step = 'EXIT'.
ENDIF.
EXIT. "Don't process STEP DISP additionally in this call.
ENDIF.
4) save and activate this function module...
5) go to se11 and create "Elementary srch hlp"....
6) fill out all the necessary fields...i am assuming that you already know how to create the search helps...
look for this field: "Search help exit" and put your function name which you created in the above steps...
in this example i have: ZF4IF_SHLP_EXIT_pernr....
7) create and activate the search help....
hope this helps...i just tested this and it is working for me....
Thanks..
AS... -
hello all,
i'm using oracle forms 6i
i create a bush-button and using trigger when button pressed
DECLARE
WHERE_CLAUSE VARCHAR2 (3000) := '';
BEGIN
WHERE_CLAUSE :='T.L_ID IN ('||:CONTROL.TXT_L2||')'
||'AND TO_NUMBER(TO_CHAR(T.M_DATE,''MM'')) IN ('||(:CONTROL.TXT_M)|| ')' ;
/* 'T.M_DATE BETWEEN'|| (:TXT_FROM) ||'AND' ||(:TXT_TO);
'T.M_DATE IN (SELECT M_DATE FROM T' ||' WHERE M_DATE BETWEEN '||(:TXT_FROM)|| ' AND ' || (:TXT_TO) || ')';*/
SET_BLOCK_PROPERTY ('T', DEFAULT_WHERE, WHERE_CLAUSE);
GO_BLOCK('T');
EXECUTE_QUERY;
END;my code is working fine when i insert value in two txt item (:CONTROL.TXT_L2 ) (:CONTROL.TXT_M)
my problem is
i would like to insert one value in one txt item
quotation 2
how can i use (between operator) in same situation
thank's all :)There is an exclusive forum for Forms: {forum:id=82}
-
Writing to a temp table in a stored procedure with dynamic sql
Hi
I am writing into a temp table with dynamic sql:
select coloum_name into #temp_table from
+
@DestinationDBName+'.information_schema.tables
and then I am trying to use #temp_table in the procedure:
select coloum_name into #anotherTable from #temp_table
but I am getting an error that #temp_table is not recognized.
Can a temp table not be used in dynamic sql ?
How can I overcome this problem ?Temp Table Can used easily in Dynamic Query in SQL Server and here is small Exmaple you can check it and do like it
CREATE PROC test
AS
BEGIN
CREATE TABLE #T1
(ID int , NAME Nvarchar(50))
CREATE TABLE #T2
(ID int , NAME Nvarchar(50))
DECLARE @SQL NVARCHAR(MAX)='Insert into #T1
SELECT database_id , Name FROM Sys.Databases
Insert into #T2 Select ID , Name from #T1 '
EXEC SP_ExecuteSQL @SQL
SELECT * FROM #T2
DROP TABLE #T1
DROP TABLE #T2
END
Exec Test
If you found My reply is helpful for you please vote me
thanks
Mustafa EL-Masry
Principle Database Administrator & DB Analyst
SQL Server MCTS-MCITP
M| +966 54 399 0968
MostafaElmasry.Wordpress.Com -
Does anyone out there use dynamic SQL with DB2? If so, are the sql statements causing a PreparedStatement to be executed on DB2. I posted this question similarly before, but never resolved it, and it is killing me. I have to resolve this ASAP!
Here is the problem: My DB2 Admin says that EVERY TIME I access the database, my Java app is causing the database to create a PreparedStatement. However, I'm using Statement objects exclusively, with dynamic SQL. He says that DB2 needs an "access path" for the client, and that it converts the Statement to a PreparedStatement, as this is the only way to get this "access path". He says the only solution is either stored procedures or SQLJ, which will do the binding in advance, and increase performance tremendously. However, I am STRONGLY opposed to using SQLJ, and if we do stored procedures, we'd have to write one for every possible SQL statment! I KNOW there is a better solution.
Is anyone out there having these problems with JDBC and DB2? Surely someone out there uses DB2 and JDBC and either has these problems or can confirm that something is incorrectly configured on the database side.
Any help would be great. Thanks, WillNow I'm wondering if maybe the PreparedStatements are ONLY being called on the database when I call getConnection(), and not when I call executeQuery() or executeUpdate() from the Statement object. I just can't see why the database would have to make an access path for every SQL statement executed, but I could see it creating an access path for every connection requested. Any thoughts on that theory?
-
Is it possible to make a search help with dynamic selection table?
Hi Experts,
Is it possible to create search helps with dynamic seletion tables means
i dont know the selection table names at the time of creation of search help.
These tables will be determined at runtime.
if yes, Please give an idea how to create and pass the table names at runtime.
Thanks
Yogesh GuptaHi Yogesh,
Create and fill your itab and show it with FM F4IF_INT_TABLE_VALUE_REQUEST
CALL FUNCTION 'F4IF_INT_TABLE_VALUE_REQUEST'
EXPORTING
retfield = 'field to return from itab'
dynpprog = sy-repid
dynpnr = sy-dynnr
dynprofield = 'field on your screen to be filled'
stepl = sy-stepl
window_title = 'some text'
value_org = 'S'
TABLES
value_tab = itab
EXCEPTIONS
parameter_error = 1
no_values_found = 2
OTHERS = 3.
Darley -
Backup DB with dynamic sql - want to substitute in dbname and disk file path
Re: Backup DB with dynamic sql - want to substitute in dbname and disk file path
Hope I can explain this. Below is a small snippet of code. I want to set @SQLTemplate_TSQL once at the top of the script and then execute the SET @SQLCommand and sp_executesql in a loop that reads a list of databases. It all works, except for the
BACKUP DATABASE. Right now it evaluates when the SET @SQLTemplate_TSQL is evaluated. I want it to evaluate when it is executed. I want the DB_NAME() of the USE @dbname.
-- change @dbname and @dbbackuppath
DECLARE @SQLCommand NVARCHAR(MAX)
DECLARE @SQLTemplate_TSQL NVARCHAR(MAX)
DECLARE @dbname varchar(128) = 'Bank04'
-- one time setting of @SQLTemplate_TSQL
set @SQLTemplate_TSQL =
DECLARE @dbbackuppath varchar(128) = ''''d:\backups''''
IF RIGHT(@dbbackuppath, 1) <> ''''\''''
SET @dbbackuppath = @dbbackuppath + ''''\''''
SET @dbbackuppath = @dbbackuppath + DB_Name() + ''''.bak''''
PRINT @dbbackuppath
BACKUP DATABASE ' + DB_NAME() + ' to DISK=''' + QUOTENAME(@dbbackuppath, CHAR(39)) + '''
-- Execute this several times over different databases
SET @SQLCommand = '
USE ' + QUOTENAME(@dbname) + ';
EXEC(''' + @SQLTemplate_TSQL + ''') '
PRINT @SQLCommand
EXECUTE sp_executesql @SQLCommandHere is a stripped down version of my code. Someone writes a script. I then take the script and seperate it by GO statement block. Each GO block gets its own row into the
#SQLTemplate_TSQL. I then replace single quote with 4 quotes and run it. Then I run against my list of databases. I am unable to get the BACKUP DATA base to work with this model.
Run scripts against multiple databases.sql
Do a FIND on "CHANGE THIS" to see the databases returned from the SELECT statement
DECLARE @DatabaseName varchar(128)
DECLARE @SQLCommand NVARCHAR(MAX)
DECLARE @SQLTemplate_Seq INT
DECLARE @SQLTemplate_OperationDesc NVARCHAR(128)
DECLARE @SQLTemplate_TSQL NVARCHAR(MAX)
DECLARE @SQLTemplate_Diagnostics INT
DECLARE @Note VARCHAR(500)
IF OBJECT_ID('tempdb..#SQLTemplate_TSQL') IS NOT NULL
DROP TABLE #SQLTemplate_TSQL
CREATE TABLE [dbo].[#SQLTemplate_TSQL](
[SQLTemplate_RecID] [int] Identity,
[SQLTemplate_ID] [int] NOT NULL,
[SQLTemplate_Seq] [int] NOT NULL,
[SQLTemplate_OperationDesc] [varchar](128) NOT NULL,
[SQLTemplate_TSQL] [varchar](max) NOT NULL,
[SQLTemplate_Diagnostics] [int] NOT NULL,
[SQLTemplate_Enabled] [int] NOT NULL)
DELETE FROM #SQLTemplate_TSQL WHERE SQLTemplate_Seq = 65
DECLARE @SeqID INT
SELECT @SeqID = MAX(SQLTemplate_ID) FROM #SQLTemplate_TSQL
SET @SeqID = ISNULL(@SeqID,0)
SET @SeqID = @SeqID + 1
INSERT INTO #SQLTemplate_TSQL VALUES(@SeqID ,65,@SeqID,'
SELECT * FROM ifs_config
',1,1)
SET @SeqID = @SeqID + 1
INSERT INTO #SQLTemplate_TSQL VALUES(@SeqID ,65,@SeqID,'
DECLARE @HistoryODS INT
SET @HistoryODS = 1
SELECT * FROM ifs_tablelist WHERE HistoryODS = @HistoryODS and Tablename like ''''%HIST%''''
',1,1)
-- Setup Cursor to Loop through each of the Prior Period databases
DECLARE db_cursor CURSOR FOR
SELECT [Database Name] --<<<<<<<< CHANGE THIS SELECT statement to select DBs >>>>>>
FROM v_ifs_PPODSDBInfo_Curr
WHERE [Database Frequency] <> 'CURRENT'
ORDER BY [Database Frequency], [Database Number]
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @DatabaseName
-- Loop through each of the databases
WHILE @@FETCH_STATUS = 0
BEGIN
-- Setup Cursor to Loop through each of the SQL Statements
DECLARE #SQLTemplate_TSQL_cursor CURSOR FOR
SELECT [SQLTemplate_TSQL], [SQLTemplate_OperationDesc], [SQLTemplate_Seq], [SQLTemplate_Diagnostics]
FROM #SQLTemplate_TSQL
WHERE [SQLTemplate_Enabled] = 1 AND SQLTemplate_Seq = 65
ORDER BY SQLTemplate_ID
OPEN #SQLTemplate_TSQL_cursor
FETCH NEXT FROM #SQLTemplate_TSQL_cursor INTO @SQLTemplate_TSQL, @SQLTemplate_OperationDesc, @SQLTemplate_Seq, @SQLTemplate_Diagnostics
-- Loop through each of the SQL statements
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQLCommand = '
USE ' + QUOTENAME(@Databasename) + ';
EXEC(''' + @SQLTemplate_TSQL + ''') '
EXECUTE sp_executesql @SQLCommand
FETCH NEXT FROM #SQLTemplate_TSQL_cursor INTO @SQLTemplate_TSQL, @SQLTemplate_OperationDesc, @SQLTemplate_Seq, @SQLTemplate_Diagnostics
END
CLOSE #SQLTemplate_TSQL_cursor
DEALLOCATE #SQLTemplate_TSQL_cursor
FETCH NEXT FROM db_cursor INTO @DatabaseName
END
CLOSE db_cursor
DEALLOCATE db_cursor -
Help with an SQL Query on the Logger
We are running UCCE 8.5(3) and need help with an SQL query. When I run the below I would also like to see skill group information(name preferably)? Any help would be greatly appreciated!
select * from dbo.t_Termination_Call_Detail where DateTime between '10-11-2012 00:00:00:00' and
'10-11-2012 23:59:59:59'David, thanks for replying. Unfortunitly I don't know enough about SQL to put that into a query and have it return data. Would you be able to give an example on what the query would look like?
-
Need help with Dynamic Excel File Name please.
I am try to output an excel file with dynamic date.
Here what I done.
I am using SQL 2012.
Create Execute SQL Task Connect Type: Excel
Create Data Flow Task set to DelayValidation: True
Create OLE DB Sourc
Create Data Converstion
Excel Destination
Excel Connection, Expression, select ExcelFilePath
@[User::sXLFilePath] + @[User::sFileName] + RIGHT("0" + (DT_WSTR, 2) DATEPART("DD", GETDATE()), 2)+ RIGHT("0" + (DT_WSTR, 2) DATEPART("MM", GETDATE()), 2) + RIGHT((DT_WSTR,
4) DATEPART("YYYY", GETDATE()), 2) +".csv"
C:\ExcelOutPut\SOX_CAM_SQL_Report_010215.xls
What I try to accomplish is output the file with each day append to it, date must be DDMMYY.
I google it and found many samples, tested it, and none of them is work for me.
Any suggestions or some examples to share is greatly appreciate.
I am new to SSIS. I found one poster have similar issue and inside the posted below, there was one suggestion to create variable and connection string but how do I bind that variable to Excel Connection manger.
Please help.
Thank you so much in advance.
Ex: SOX_CAM_SQL_Report _020215.csv
SOX_CAM_SQL_Report _030215.csv
--Similar issue:
https://social.msdn.microsoft.com/Forums/en-US/bda433aa-c8f8-47c9-9e56-efd20b8354ac/creating-a-dynamic-excel-file?forum=sqlintegrationservices
Suggestion in the above posted but where can bind this to Excel Connection Manger.
Please help provide step by step. Thanks.
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\temp\\" + "ExcelTarget" + (DT_WSTR,4)DATEPART("yyyy",GETDATE()) +
".xls" + ";Extended Properties=\"EXCEL 8.0;HDR=YES\";"
And yes, as you were intimating, the delay validation on the dataflow should be set.Hi NguyenBL,
According to your description, you created ssis package to export data from database to excel, when the package runs, you want to create new excel and name the file with time stamp. If that is the case, we can achieve the goal by following steps:
Create a script task used to create excel files.
Create a data flow task to export data from database to excel.
Add OLE DB source to data flow task.
Add Excel Destination to data flow task.
Create connection manager for OLE DB and Excel.
Click Excel Connection Manager, in Properties window, click (…) button next to Expressions, then set ExcelFilePath with expression like below:
"C:\\ETL Lab\\CreateNewExcel\\ExportData_"+REPLACE((DT_STR, 20, 1252)(DT_DBTIMESTAMP)@[System::StartTime], ":", "")+".xls"
For detail information, please refer to the document:
https://sqljourney.wordpress.com/2013/01/12/ssis-create-new-excel-file-dynamically-to-export-data/
If you have any more questions, please feel free to ask.
Thanks,
Wendy Fu
Wendy Fu
TechNet Community Support -
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 -
Hello,
I would like to create a Dynamic SQL in which change is the name of the table according to the outcome of the first SQL. This is possible?
'WITH TABLE_X AS(SELECT LEVEL LVL FROM DUAL CONNECT BY LEVEL <= 12)' ||
'SELECT A.COL1, A.COL2, B.COL1, B.COL7' ||
' FROM TABLE_A' || TABLE_X.LVL || ' A' ||
' , TABLE_B' || TABLE_X.LVL || ' B' ||
' WHERE A.COL1 = B.COL1 AND ... 'tables in database
TABLE_A1
TABLE_A2
TABLE_A12
TABLE_B1
TABLE_B2
TABLE_B12let me know how I can do this
RegardsHi,
Sorry, I don't see what you're trying to do.
"Dynamic SQL" is really a mis-nomer. The number of tables and columns in a query, and their names, must be spelled out when the statement is compiled. There is nothing dynamic about it.
In dynamic SQL, a PL/SQL procedure or another query writes all or part of query just milliseconds before it is compiled, typically using data taken from tables or supplied by a user right then.
For example, consider this static query:
SELECT a.col1, a.col2, b.col1, b.col7
FROM table_1 a
, table_2 b
WHERE a.col1 = b.col1;Now, say the 1 in "table_1" and the 2 in "table_2" are variables, x and y, that you will want to look up from another table every time you run this query. You can make it dynamic like this:
sql_txt := 'SELECT a.col1, a.col2, b.col1, b.col7 '
|| 'FROM table_' || TO_CHAR (x) || ' a '
|| ', table_' || TO_CHAR (y) || ' b '
|| 'WHERE a.col_1 = b.col1';Now let's make it really interesting. Say that instead of 2 tables, and 1 join condition, you''ll have n tables and n-1 join conditions, where n has to be computed at (actually a split second before) run-time. That is, if n=4, you might need to construct a static query with 4 tables and 3 join conditions, like this:
SELECT a.col1, a.col2, b.col1, b.col7
FROM table_1 a
, table_2 b
, table_12 c
, table_2 d
WHERE a.col1 = b.col1
AND a.col1 = c.col1
AND a.col1 = d.col1;You can do that using dynamic SQL, too.
Post an example of the static query you need to build, and describe what parts of it are dynamic, and how you get the values for those parts, and someone will help you write the dynamic SQL. -
Erratic Report Region Behavior with Dynamic SQL Queries
I'm running HTMLDB v 1.5.1.00.12 and I've noticed some odd behavior with report regions using dynamic SQL queries. Every so often, our testers will run a page containing a dynamic sql report region and get the following error, (despite the fact the query was working only moments ago and no other developer has touched it):
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
or sometimes
failed to parse SQL query:ORA-01403: no data found
The only solution I've found so far is to:
1) Make a copy of the failed report region.
2) Disable or delete the original failed report region.
The new copy of the report region runs without issue.
My search of the forums turned up the following two threads, but neither provided me with a clear explanation of the cause, and how to avoid it:
ORA-06502:PL/SQL: numeric or value error: character string buffer too small
Re: Import Export Error (ORA-06502)
The columns being returned are below the 4000 character limit, and the rows being returned are far less than 32k in size.
Could this have anything to do with the way HTMLDB is internally storing the PL/SQL used to generate the dynamic SQL Query? Is there any known issue related to this with that version of HTMLDB?
This problem occurs without any discernable pattern or consistency, making it hard to determine where I should focus my efforts in tracking down the cause.Hi all,
My report seems to be behaving correctly once i set it to "Use Generic Column Names (parse query at runtime only)" :)
Cheers,
Joel -
Using bind variables (in & out) with dynamic sql
I got a table that holds pl/sql code snippets to do validations on a set of data. what the code basically does is receiving a ID and returning a number of errors found.
To execute the code I use dynamic sql with two bind variables.
When the codes consists of a simpel query, it works like a charm, for example with this code:
BEGIN
SELECT COUNT (1)
INTO :1
FROM articles atl
WHERE ATL.CSE_ID = :2 AND cgp_id IS NULL;
END;however when I get to some more complex validations that need to do calculations or execute multiple queries, I'm running into trouble.
I've boiled the problem down into this:
DECLARE
counter NUMBER;
my_id NUMBER := 61;
BEGIN
EXECUTE IMMEDIATE ('
declare
some_var number;
begin
select 1 into some_var from dual
where :2 = 61;
:1 := :2;
end;
USING OUT counter, IN my_id;
DBMS_OUTPUT.put_line (counter || '-' || my_id);
END;this code doesn't really make any sense, but it's just to show you what the problem is. When I execute this code, I get the error
ORA-6537 OUT bind variable bound to an IN position
The error doesn't seem to make sense, :2 is the only IN bind variable, and it's only used in a where clause.
As soon as I remove that where clause , the code will work again (giving me 61-61, in case you liked to know).
Any idea whats going wrong? Am I just using the bind variables in a way you're not supposed to use them?
I'm using Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bitCorrection. With execute immediate binding is by position, but binds do not need to be repeated. So my statement above is incorrect..
You need to bind it once only - but bind by position. And the bind must match how the bind variable is used.
If the bind variable never assigns a value in the code, bind as IN.
If the bind variable assigns a value in the code, bind as OUT.
If the bind variable assigns a value and is used a variable in any other statement in the code, bind as IN OUT.
E.g.
SQL> create or replace procedure FooProc is
2 cnt number;
3 id number := 61;
4 begin
5 execute immediate
6 'declare
7 n number;
8 begin
9 select
10 1 into n
11 from dual
12 where :var1 = 61; --// var1 is used as IN
13
14 :var2 := n * :var1; --// var2 is used as OUT and var1 as IN
15 :var2 := -1 * :var2; --// var2 is used as OUT and IN
16 end;
17 '
18 using
19 in out id, in out cnt; --// must reflect usage above
20
21 DBMS_OUTPUT.put_line ( 'cnt='||cnt || ' id=' || id);
22 end;
23 /
Procedure created.
SQL>
SQL> exec FooProc
cnt=-61 id=61
PL/SQL procedure successfully completed.
SQL> -
Problems while creating a Java stored proc with dynamic SQL
Hi,
I am trying to write a stored procedure which uses dynamic SQL. The code runs fine outside the database (on DOS PROMPT),but gives me an exception when I try to execute it as a procedure. Could somebody help me out?
The exception given is:
ERROR at line 1:
ORA-29532: Java call terminated by uncaught Java exception:
java.security.AccessControlException: the Permission (java.net.SocketPermission
elcamino.mcasolutions.com resolve) has not been granted by
dbms_java.grant_permission to SchemaProtectionDomain(SPO|PolicyTableProxy(SPO))
Does it have anything to access permissions to that user?
Thanks in advance!
JoeHi:
This store procedure is a Java stored procedure (JSP)?
If true, change your Java code to connect to database because you are connected.
For example:
Connection con = new OracleDriver().defaultConnection();
instead of
Connection con = DriverManager.getConnection(..);
Bye.
J.
Maybe you are looking for
-
How to maintain more users in jsp page
i need a multi user login. each user should have thier own username and password (supplied by me) then each user should have their own page
-
I am about to view an encrypted page that contains some unencrypted information and there is an Ok button should I click on the Ok button.
-
Do the new iPods output video at the newly supported 640x480 resolution or do they output the scaled version of the video that they display on their own screens? Same question for the old 5G iPods with the updated firmware. Thanks.
-
I was just curious if anyone knew how to change the icon which appears next to the song title on the "now playing" screen. I have some mp3s that are shown with album art of completely different artists and it's really unfortunate to see, for instance
-
What is the solution to an iphone 3g that blanked out?
what is the solution to an iphone 3g that blanked out?