Generating DDL from ResultSetMetaData
Hi, I'm new to this forum although you can occasionally spot me on some of the other forums at java.sun.com. So if this is not the correct place for my question, I would appreciate a pointer to a more appropriate location.. -- Thanks
I was wondering if anyone knew of a utility to create a DDL from a ResultSetMetaData. I'm sure I could develop one with some time, but it's for a one-off project. There is a huge Stored Procedure that someone else is going to analyze for performance. But it's speed is slowing down my testing, and I would like to create a temporary table with the results from that SP, but I don't want to manually format the hundreds of columns involved. The information needed to create the table is clearly stored in the ResultSetMetaData associated with a call to the StoredProcedure, but I don't know any way to convert that into some sort of script.
Any suggestions?
This is on SQL Server, and I'm not particularly familiar with it, so if anyone knows a native trick for this DBMS, that would be appreciated too.
Thanks,
-- Scott
Never mind. I got it. When I came back to this after lunch, I realized both that this would likely not be a one-off, and that it shouldn't be too hard for my limited needs. The code I used is below. This is specific to SQL Server, and only to a limited number of data types, but it would be easy to extend to other's simple needs. I'm sure there are robust versions easily available, but I didn't find them. In the following code, rs is a ResultSet:
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
System.out.println("IF EXISTS (SELECT * FROM dbo.sysobjects WHERE" +
" id = object_id(N'[dbo].["
+ tableName + "]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)");
System.out.println("DROP TABLE [dbo].[" + tableName + "]");
System.out.println("GO");
System.out.println();
System.out.println("CREATE TABLE [dbo].[" + tableName + "] (");
for(int i = 1; i <= colCount; i++) {
String type = rsmd.getColumnTypeName(i);
System.out.print("\t" + ((i > 1) ? "[" : ""));
System.out.print(rsmd.getColumnName(i) + ((i > 1) ? "] [" : " "));
System.out.print(type + ((i > 1) ? "] " : " "));
if (type.equals("varchar") || type.equals("char")) {
System.out.print("(" + rsmd.getPrecision(i) + ") ");
} else if (type.equals("decimal")) {
System.out.print("(" + rsmd.getPrecision(i) + ", " + rsmd.getScale(i) + ") ");
} else if (!(type.equals("uniqueidentifier")
|| type.equals("datetime") || type.equals("int"))) {
throw new IllegalArgumentException(
"stupid DDL generator can't handle type \"" + type + "\".");
int nullableInt = rsmd.isNullable(i);
if (nullableInt == ResultSetMetaData.columnNoNulls) {
System.out.print("NOT NULL");
} else if (nullableInt == ResultSetMetaData.columnNullable) {
System.out.print("NULL");
if (i < colCount) {
System.out.print(" ,");
System.out.println();
System.out.println(")");
System.out.println("GO");
System.out.println();
while(rs.next()) {
System.out.print("INSERT INTO " + tableName + " VALUES (");
for(int i = 1; i <= colCount; i++) {
String type = rsmd.getColumnTypeName(i);
boolean quoted = (type.equals("char") || type.equals("varchar") ||
type.equals("uniqueidentifier") || type.equals("datetime"));
if (i > 1) System.out.print(",");
Object temp = rs.getObject(i);
String value = (temp == null) ? "NULL" : temp.toString();
if (quoted && temp != null) {
System.out.print("'");
System.out.print(value);
if (quoted && temp != null) {
System.out.print("'");
System.out.println(");");
}I know this is far from elegant, and too specific to my small problem, but anyone who needs something similar should be able to modify it rather easily.
-- Scott
Similar Messages
-
Generating DDL from Server Model
I would like to generate DDL that matches ERDs from the server model in Designer. However, when selecting an application folder, and expanding Relational Tables, I see a lot of tables I don't recognize - they aren't entities in the ERD. I don't know where they came from, and some of the ERD entities aren't showing up in the server model. I just want to generate DDL that creates only the tables shown in the ERD. Any way to do this?
About your question for more complex constraints. That is not possible in Designer.
If you are using Headstart, you can achieve this by using CDM RuleFrame. This is a way to record all types of (complex) constraints (business rules).
see http://www.oracle.com/technology/products/headstart/index.html for more information. -
Generating DDL from SQL Workshop
I'm using the Database Cloud Service and am trying to see how I can generate DDL for my tables.
I looked into the online help, which led me to this:
http://docs.oracle.com/cd/E37097_01/doc/doc.42/e35128/sql_utl.htm#AEUTL256
Says to click SQL Workshop -> Utilities -> Generate DDL, but there is no Generate DDL option. Has the option moved or the name changed?
Thanks,
RickHello Rick -
The easiest way to get DDL for the tables in your Database Cloud Service is to go to the Cloud Management UI for your Service and click on the Data Export tab. Click on the Export Data button and just do not check the box for exporting data. This will give you DDL for your Service.
Hope this helps.
- Rick Greenwald -
Possible to generate DDL from outside of JDeveloper?
Hi:
I was wondering if it is possible to have a build script somehow generate the DDL for a database from the model files that JDeveloper creates (in the same way one would run a SQL Plus script from the command line passing a .sql file for it). This is desirable because my project wants to keep a database schema under CM but not multiple files that have to be kept in sync (like the model files AND the DDL).
Thanks.Got it! I was able to extend the "New Presentation" sample to allow users to save their newly-created presentations back to the BI catalog. Here's how:
1) add a menu item for "Save"; add a listener for it
m_mnuSave = new JMenuItem("Save...");
m_mnuSave.setMnemonic('S');
fileMenu.add(m_mnuSave, 4);
m_mnuSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mnuSave_ActionPerformed(e);
2) in mnuNew_ActionPerformed, add code to save the presentation to a module-level variable
Dataview dv = npw.getDataview();
m_objPresentation = npw.getDataview(); // new code
3) write the Save action handler
void mnuSave_ActionPerformed(ActionEvent e) {
String sName = "";
int result = 0;
if (m_objPresentation == null)
JOptionPane.showMessageDialog(null, "No presentation to be saved");
return;
/* Create InitialPersistenceManager */
InitialPersistenceManager pmRoot = (InitialPersistenceManager)getPersistenceManager();
/* Create PersistenceObjectChooser */
PersistenceObjectChooser dialog = new PersistenceObjectChooser(pmRoot);
JFrame frame = new JFrame();
result = dialog.showSaveDialog(frame);
if (result == PersistenceObjectChooser.OK_OPTION)
PersistenceManager pmCurrent = (PersistenceManager)dialog.getCurrentDirectory();
sName = dialog.getSelectedObjectName();
if (sName != null)
try
//if name is not bound, then rebind will bind it
pmCurrent.rebind(sName, m_objPresentation);
catch (Exception ex) {
showExceptionDialog(this, ex);
} // if sName != null
}// if result == OK_OPTION -
Generating DDL From Designer In a Set Order
Hi,
Designer Version is 10.1.2.0.2.
Whenever I generate the schema/ddl creation scripts after making minor
changes, I like to compare the new scripts against the last set just to
make sure the changes are as I expect. The trouble is each time I
regenerate, the order of the items is different each time, making
comparisons difficult.
I've tried looking for a setting in the preference sets but there isn't
anything obvious . Anyone know how to tell it to set the order of the
tables during generation?
Regards
SandeepWhat has "Designer" got to do with SQL and PL/SQL? Please ask your question in the correct forum.
-
SQL*Developer 2.1 - Not Generating DDL for Different Users
Using SQL*Developer Version 2.1.0.63 I get an error trying to generate DDL from another user, that has access to many other schemas. It looks to me like Sql Developer is calling the DBMS_METADATA package from within other PL/SQL.
I am receiving the following error:
ORA-31603: object "ACCOUNT_TYPE_LKP" of type TABLE not found in schema "POR_OWN"
ORA-06512: at "SYS.DBMS_SYS_ERROR", line 105
ORA-06512: at "SYS.DBMS_METADATA", line 3241
ORA-06512: at "SYS.DBMS_METADATA", line 4812
ORA-06512: at line 1
I would receive these same errors in SQL Developer 1.5, but the DDL would still generated. It was picking something up, even though it had an error.
Our DBA has not been able to provided a work around. He says you have to login directly as the owner of the objects to use dbms_metdata in this fashion.
Is there any work around for this? I really need to be able to get DDL and I do not want to go back to 1.5 (I like the other new features of 2.1).
Thanks,
TomWe have several users currently using SQL Navigator and/or TOAD. We would like them to switch to SQL developer, but part of their job is to view the source of views in another schema. They have select privileges on the underlying tables and are able to see the source using other tools. Using SQL Developer, they receive on ORA-31603 because it's calling dbms_meta. Note ID 1185443.1 describes the issue and suggests granting the users the SELECT_CATALOG_ROLE.
We are hesitant about granting this role to these users which allows access to ever 1,700 objects, plus execute privileges to 4 objects.
Support indicated that Enhancement Request 8498115 addresses this issue.
Is this something that may be addressed in the next release?
Thanks,
Paul -
Generate DDL formatting data incorrectly
Greetings all,
So I appear to have found the issue with my Generated DDL File. It is formatting the lines incorrectly and I have to manually go in and clean it up.
For example:
ALTER TRIGGER "BI_MIMPBM_CA_GROUP_LKP" ENABLE;CREATE OR REPLACE TRIGGER "BI_MIMPBM_CAT_LKP"
before insert on "MIMPBM_CAT_LKP"
for each row
begin
if :NEW."CATID" is null then
select "CAT_LKP_SEQ".nextval into :NEW."CATID" from dual;
end if;
end;Notice how the ENABLE;CREATE are on the same line. That throws an error. I am not sure why as I thought the ; ended a piece of code, but when I do a carriage return on it and then put it in, it works. I am using Application Express 4.0.2.00.07 and not sure if it is the application or something I am doing in the formatting of my code when I create anything.
Is anyone else having this issue when generating DDL files? If so, is there a work around besides going through the whole script and adding carriage returns as necessary?
Thanks
WallyIs Page 5 of Data Modeling (How to generate DDL(sql) scripts to create a database) of any help?
-
Generating DDL to accept user input parameters
I need generate DDL which will accept input parameters from user, for example, tablespace name for indexes. What is the best way to do it?
At present, I’ve created tablespace with name ‘&INDEX_TS’ in physical model and using it to create indexes. Is this a correct way to do it?
Also, &INDEX_TS appears within double quotes in generated DDL. Is there a way to get rid of double quotes?
I'm using v3.1Hi,
I have just found out that there is a "substitution variable" facility within SQL*Plus and SQL Developer which allows runtime substitution when applying DDL.
Here are some extracts from the SQL Developer Help:
Script Runner
The SQL*Plus features available in the script runner include @, @@, CONNECT, EXIT, QUIT, UNDEFINE, WHENEVER, and substitution variables. For example, to run a script named c:\myscripts\mytest.sql, type @c:\myscripts\mytest in the Enter SQL Statement box, and click the drop-down next to the Execute Statement icon and select Run Script.
The following considerations apply to using the SQL Developer script runner:
For substitution variables, the syntax &&variable assigns a permanent variable value, and the syntax &variable assigns a temporary (not stored) variable value.
So if the name starts with &&, it will only prompt for the actual name the first time it appears.
Note that this still works if the name is presented as a quoted identifier, e.g.
TABLESPACE "&&INDEX_TS"
David -
How to get ddls from sqlplus like that of TOAD
Hi,
I have to work on a terminal machine for a client where the TOAD is not installed. For my regular DBA activities I need to take the DDL many times.
I am very much used to the style of DDL scripts which TOAD 9.6.x.x gives for any object in a schema.
Can someone suggest how I can I get exactly TOAD-like scripts (which provide not just the create statements)
For e.g.
*1.From sqlplus when I do*
select dbms_metadata.get_ddl('TABLE','APE1_ACCUMULATORS') from dual;
I get only the below
CREATE TABLE XLTDBO92.APE1_ACCUMULATORS
CYCLE_CODE NUMBER(4) CONSTRAINT APE1ACCU_CYCLE_CODE_NN NOT NULL,
CYCLE_INSTANCE NUMBER(2) CONSTRAINT APE1ACCU_CYCLE_INSTANCE_NN NOT NULL,
CUSTOMER_SEGMENT NUMBER(4) CONSTRAINT APE1ACCU_CUSTOMER_SEGMENT_NN NOT NULL,
CUSTOMER_ID NUMBER(9) CONSTRAINT APE1ACCU_CUSTOMER_ID_NN NOT NULL,
ACCUM_TYPE_ID NUMBER(9) CONSTRAINT APE1ACCU_ACCUM_TYPE_ID_NN NOT NULL,
OWNER_ID
*2.But from TOAD 9.6.x.x when i click on "create scripts" I will get*
DROP TABLE XLTDBO92.APE1_ACCUMULATORS CASCADE CONSTRAINTS;
CREATE TABLE XLTDBO92.APE1_ACCUMULATORS
CYCLE_CODE NUMBER(4) CONSTRAINT APE1ACCU_CYCLE_CODE_NN NOT NULL,
CYCLE_INSTANCE NUMBER(2) CONSTRAINT APE1ACCU_CYCLE_INSTANCE_NN NOT NULL,
CUSTOMER_SEGMENT NUMBER(4) CONSTRAINT APE1ACCU_CUSTOMER_SEGMENT_NN NOT NULL,
CUSTOMER_ID NUMBER(9) CONSTRAINT APE1ACCU_CUSTOMER_ID_NN NOT NULL,
ACCUM_TYPE_ID NUMBER(9) CONSTRAINT APE1ACCU_ACCUM_TYPE_ID_NN NOT NULL,
OWNER_ID
DROP SYNONYM XLTDB92.APE1_ACCUMULATORS;
CREATE SYNONYM XLTDB92.APE1_ACCUMULATORS FOR XLTDBO92.APE1_ACCUMULATORS;
GRANT DELETE, INSERT, SELECT, UPDATE ON XLTDBO92.APE1_ACCUMULATORS TO XLTDBO92_ALL;
So my question is:
How to such scripts from sqlplus as well ,irrespective of the type of the object?_
Note:I am posting a new thread because my previous question was answered even though i was not able to type in completely. My mistake as it was posted in before i could finish the question.
Regds,
KunwarIf the DDL returned by dbms_metadata is not to your liking then write your own scrips to generate DDL or cover scripts to generate all related items that you want.
In the case of synonyms and grants this is very easy using rdbms dictionary views, but if you generate a table's DDL you may also want and need the PK, UK, FK, secondary indexes, comments, and policies on the table as well as synonyms and grants. Everything that if you drop the tables goes away.
There is a dbms_metaddata procedure get_dependent_ddl to generate dependend objects on a table that may be of interest.
HTH -- Mark D Powell -- -
DM 3.0.0.665 instead of triggers not generating DDL correctly
There seems to be a bug in the DDL generation for manually created INSTEAD OF triggers on views. The INSTEAD OF trigger does not have the INSTEAD OF clause upon DDL generation. Instead, it has the BEFORE clause. It seems to be treating INSTEAD OF triggers as normal triggers. Note: When I reversed engineered a database that already had an INSTEAD OF trigger, it imported and generated DDL was fine. This bug shows itself when manually creating INSTEAD OF triggers.
Steps to replicate:
1. In any design that has a view.
2. In the physical model, find the view, expand it, right click to create Trigger for view
3. By definition, a trigger on a view can only be an instead of trigger.
4. The dialog box will have the 'Triggering time' showing as INSTEAD OF. You can't change it. (Which there is no reason to do anyway)
5. Generate DDL. When generating the DDL, the trigger will not be generated as INSTEAD OF, it will be generated as a BEFORE (INSERT/UPDATE/DELETE).
Included DDL generation from a simple database (I did not modify the DDL generated):
-- Generated by Oracle SQL Developer Data Modeler 3.0.0.665
-- at: 2011-03-30 13:16:32 EDT
-- site: Oracle Database 10g
-- type: Oracle Database 10g
-- CREATE DATABASE DB2
-- CONTROLFILE REUSE
-- MAXLOGFILES 1
-- MAXLOGMEMBERS 1
-- MAXLOGHISTORY 0
-- MAXDATAFILES 10
-- MAXINSTANCES 1
-- ARCHIVELOG
-- FORCE LOGGING
-- DATAFILE
-- '' SIZE 0 K REUSE
CREATE TABLE TABLE_1
Column_1 VARCHAR2 (1)
) LOGGING
CREATE OR REPLACE VIEW VIEW_1 ( Column_1 )
AS SELECT
TABLE_1.Column_1
FROM
TABLE_1 TABLE_1 ;
CREATE OR REPLACE TRIGGER Trg1
BEFORE INSERT ON VIEW_1
FOR EACH ROW
BEGIN
NULL;
END;
-- Oracle SQL Developer Data Modeler Summary Report:
-- CREATE TABLE 1
-- CREATE INDEX 0
-- ALTER TABLE 0
-- CREATE VIEW 1
-- CREATE PACKAGE 0
-- CREATE PACKAGE BODY 0
-- CREATE PROCEDURE 0
-- CREATE FUNCTION 0
-- CREATE TRIGGER 1
-- CREATE STRUCTURED TYPE 0
-- CREATE COLLECTION TYPE 0
-- CREATE CLUSTER 0
-- CREATE CONTEXT 0
-- CREATE DATABASE 1
-- CREATE DIMENSION 0
-- CREATE DIRECTORY 0
-- CREATE DISK GROUP 0
-- CREATE ROLE 0
-- CREATE ROLLBACK SEGMENT 0
-- CREATE SEQUENCE 0
-- CREATE MATERIALIZED VIEW 0
-- CREATE SYNONYM 0
-- CREATE TABLESPACE 0
-- CREATE USER 0
-- DROP TABLESPACE 0
-- DROP DATABASE 0
-- ERRORS 0
-- WARNINGS 0Hi,
Thanks for reporting this problem. I logged a bug on it.
David -
Generate DDL - change is a new column and I want to generate a alter table
Morning all,
I have searched and looked all over the data modeler and I cannot find this option ... yet I did find it easily in Designer.
I hope you can help me.
SQL Developer Data Modeler v3.0.0.665.
I have added a new column to a table and when I generate the DDL I would like it to be an alter table add column rather than a create table.
This feature is in Designer so I would think it would be in data modeler.
Just incase my description is not clear here are the high level steps so it is clear.
1. create the logical model
2. create the relational from the logical.
3. create the physical from the relational.
4. generate DDL and run in database. At this point I go to production with my system and all is well.
5. At this point we have an enhancement request. For the model it will be a new column in a table.
6. update logical model.
7. update relational from logical
8. update physical from relational
9. generate DDL. Here I would like to have the generate be aware the it needs only to generate an alter table add column and not create the table.
This is something I do alot as all my models are in production. I cannot find how to do this step of getting data modeler to generate the alter.
Designer does this exceptionally well.
Quite often it is more than a single column. The changes can be many and made over time and at the time of generating the DDL you may not recall every single change you made. To have the tool discover those changes for you and generate the appropriate DDL is a feature I regard as very high.
I hope this is clear and you can help me.
Cheers
Chris ....Hi Chris,
you need to compare your model against database - import from database into same relational model and use "swap target" option - in this case "alter statements" against database will be generated.
You can look at demonstrations here http://www.oracle.com/technetwork/developer-tools/datamodeler/demonstrations-224554.html
Probably this particular one will be most helpful http://download.oracle.com/otn_hosted_doc/sqldev/importddl/importddl.html
Soon or later your changes will require table to be recreated and you'll need to backup your data - you can consider usage of "Advanced DDL" option - script will be generated that will unload the content of your table (including LOBs) to file system accessible from database and restore it after changes. Well don't try it directly on production system :).
Philip -
Crash while generating SQL from offline DB
Hi,
I just got the following exception from the JDeveloper 10.1.3.0.2.223 preview version while trying to generate SQL from an offline database.
Stack trace:
java.lang.ArrayIndexOutOfBoundsException: 1
at oracle.jdeveloper.offlinedb.handler.GenerateSQLHandler.copySchemaObjects(GenerateSQLHandler.java:424)
at oracle.jdeveloper.offlinedb.handler.GenerateSQLHandler.handleReconcileSQL(GenerateSQLHandler.java:245)
at oracle.jdeveloper.offlinedb.handler.GenerateSQLHandler.handleReconcileSQL(GenerateSQLHandler.java:217)
at oracle.jdeveloper.offlinedb.wizard.GenerateWizard.invokeGenerateWizard(GenerateWizard.java:176)
at oracle.jdeveloper.dbmodeler.diagram.registry.RDatabaseDiagramComponent$DDLReceiver.onCheckedCmdUIEvent(RDatabaseDiagramComponent.java:335)
at oracle.bm.diagrammer.cmdUI.CmdUIReceiver$Checked.onCmdUIEvent(CmdUIReceiver.java:97)
at oracle.bm.diagrammer.BaseDiagram$1.onCmdUIEvent(BaseDiagram.java:337)
at oracle.bm.addinUtil.IDEAppContext.handledElseWhere(IDEAppContext.java:1816)
at oracle.bm.addinUtil.IDEAppContext.onCmdUI(IDEAppContext.java:1744)
at oracle.bm.addinUtil.IDEAppContext.handleEvent(IDEAppContext.java:3863)
at oracle.ide.IdeAction.performAction(IdeAction.java:661)
at oracle.ide.IdeAction$2.run(IdeAction.java:889)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:234)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
Has anybody else experienced this problem too?
Vahan Harput
[email protected]Hi Lisa,
My complete DDL:
CREATE TABLE "GENRE"
"GENRE" NVARCHAR2 (100) NOT NULL
CREATE TABLE "MEDIA"
"ID" NUMBER NOT NULL,
"TYPE" CHARACTER (1)
CREATE TABLE "MOVIE"
"ID" NUMBER,
"NAME" NVARCHAR2 (1000),
"GENRE" NVARCHAR2 (100) NOT NULL,
"MEDIA_ID" NUMBER NOT NULL
ALTER TABLE "GENRE"
ADD CONSTRAINT "GENRE_PK" PRIMARY KEY
"GENRE"
ENABLE
ALTER TABLE "MEDIA"
ADD CONSTRAINT "MEDIA_PK" PRIMARY KEY
"ID"
ENABLE
ALTER TABLE "MOVIE"
ADD CONSTRAINT "MOVIE_FK_GENRE" FOREIGN KEY
"GENRE"
REFERENCES "GENRE"
"GENRE"
) ENABLE
ALTER TABLE "MOVIE"
ADD CONSTRAINT "MOVIE_FK_MEDIA" FOREIGN KEY
"MEDIA_ID"
REFERENCES "MEDIA"
"ID"
) ENABLE
CREATE SEQUENCE "MEDIA_SEQ" INCREMENT BY 1 START WITH 1 ;
CREATE SEQUENCE "MOVIE_SEQ" INCREMENT BY 1 START WITH 1 ;
Regards,
Vahan Harput -
Invalid grants in omwb generated ddl
The sybase database I am migrating from appears to have granted 'update statistics', 'delete statistics', and 'truncate table' privileges on specific tables. The omwb generated grant statements for these privileges in the ddl which is invalid. I likely will be generating scripts for this database as well as others quite a bit over the next few months I was wondering if there is a way to configure either before/after capturing the source to prevent it from making its way into the generated ddl.
thanksHello,
After your capture /convert, you can generate the migration scripts to a file instead of creating the database directly from the OMWB.
Action > Generate Migration Scripts
You can then modify the script to your needs . Then run it in SQL*Plus to create your database.
I hope this helps
Dermot -
Apostrophes (single quote) are lost when generating DDL code.
Hi,
ODI Version : 11.1.1.5.0
Java version : 1.6.0_24
Database version : Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
Context: Generating DDL code for a an ODI Model
PROBLEMATIC: When generating DDL code, all apostrophes (single quote: ') are removed from Datastore Descriptions and Datastore Colunms Descriptions in the process of generating Comments on Tables and Comments on Tables Columns. I tried to double, even triple apostrophes (in descriptions), without success. I also tried double quotes (") without success either.
Ex: Datastore Column Description: *+ID de l'utilisateur+* becomes *+comment on table ... is 'ID de l utilisateur'+* in generated procedure.
Do you know a way to keep the apostrophes when creating Comments on Columns and Oracle Tables by generating DDL code ?
Regards,
Gaston
Edited by: uleblga on 23-May-2012 3:42 PM
Edited by: uleblga on 23-May-2012 3:42 PMNobody has a clue as how to handle this problem ?
Regards,
Gaston -
Generate DDL for objects (just for fun)
I'm been putting together queries that generate DDL. Considering exp/imp ROWS=0 can be used, or DBMS_METADATA there is little point. Though, with restricted access those may not be possible options, but then an external tool like TOAD could do it. Therefore, my justification for this is "just for fun".
Here is one for TABLEs. It does not generate the CONSTRAINTs (which i try to get in the next query), and no storage clauses. This query is also formatted for fixed width font with tabs equivalent to eight characters:
SELECT
SUBSTR
REPLACE
CASE
WHEN Columns.Column_Id = 1 THEN
'CREATE TABLE ' || Columns.Table_Name
|| CHR(10) || '('
|| CHR(10)
END
|| ' ' || Columns.Column_Name
|| RPAD(CHR(09), Tabs - FLOOR((LENGTH(Column_Name) +1) / 8), CHR(09))
|| Data_Type
|| CASE
WHEN Data_Type IN ('CHAR', 'VARCHAR2') THEN '(' || Char_Length || ')'
WHEN Data_Type = 'FLOAT' THEN '(' || Data_Precision ||')'
WHEN Data_Type = 'NUMBER' THEN
CASE WHEN Data_Precision IS NOT NULL THEN '(' || Data_Precision
|| CASE WHEN Data_Scale IS NOT NULL THEN ', ' || Data_Scale END
||')'
END
END
|| CASE
WHEN Data_Default IS NOT NULL
THEN
RPAD
CHR(09),
CASE Data_Type
WHEN 'CHAR' THEN CASE Char_Length WHEN 1 THEN 2 ELSE 1 END
WHEN 'DATE' THEN 2
ELSE 1
END,
CHR(09)
|| 'DEFAULT '
|| (
SELECT
ExtractValue
DBMS_XMLGEN.GetXMLType
SELECT
Data_Default
FROM
All_Tab_Columns
WHERE
Owner = ''' || Columns.Owner || '''
AND Table_Name = ''' || Columns.Table_Name || '''
AND Column_Name = ''' || Columns.Column_Name ||'''
'ROWSET/ROW/DATA_DEFAULT'
FROM
Dual
END
|| CASE
WHEN Columns.Column_Id = Info.Total_Columns
THEN CHR(10) || ');' || CHR(10) || CHR(10)
ELSE ','
END,
',' || CHR(10) || CHR(10),
',' || CHR(10)
1,
181
) Statement
FROM
All_Tab_Columns Columns,
SELECT
Owner,
Table_Name,
MAX(Column_Id) Total_Columns,
MAX(FLOOR((LENGTH(Column_Name) + 1) / 8)) + 1 Tabs
FROM
All_Tab_Columns
WHERE
Owner = 'SYS'
GROUP BY
Owner,
Table_Name
) Info
WHERE
Columns.Owner = Info.Owner
AND Columns.Table_Name = Info.Table_Name
ORDER BY
Columns.Owner,
Columns.Table_Name,
Columns.Column_Id;This next query get CONSTRAINTs. No formatting is used, because it becomes quite unweildy (though, if it used multiple lines, that would change). Another interesting thing is whether the CONSTRAINT names were generated or not. If they were generated, this still uses the old name and does not generate a new one:
WITH
Cons_Columns
AS
SELECT
Owner,
Constraint_Name,
SUBSTR
REPLACE
REPLACE
XMLAgg(XMLElement("A", Column_Name)
'<A>',
'</A>'
4
) || '"' List
FROM
SELECT
Owner,
Constraint_Name,
Column_Name
FROM
All_Cons_Columns
ORDER BY
Position
GROUP BY
Owner,
Constraint_Name
SELECT
'ALTER TABLE ' || Table_Name
|| ' ADD CONSTRAINT ' || Constraint_Name
|| ' '
|| CASE Constraint_Type
WHEN 'C' THEN 'CHECK'
WHEN 'U' THEN 'UNIQUE'
WHEN 'P' THEN 'PRIMARY KEY'
WHEN 'R' THEN 'FOREIGN KEY'
END
|| '('
|| CASE
WHEN Constraint_Type = 'C' THEN
SELECT
ExtractValue
DBMS_XMLGEN.GetXMLType
SELECT
Search_Condition
FROM
All_Constraints
WHERE
Owner = ''' || Cons.Owner || '''
AND Constraint_Name = ''' || Cons.Constraint_Name || '''
'ROWSET/ROW/SEARCH_CONDITION'
FROM
Dual
WHEN Constraint_Type IN ('P', 'R', 'U') THEN
SELECT
List
FROM
Cons_Columns
WHERE
Cons_Columns.Owner = Cons.Owner
AND Cons_Columns.Constraint_Name = Cons.Constraint_Name
END
|| ')'
|| CASE Constraint_Type
WHEN 'R' THEN
SELECT
' REFERENCES (' || List || ')'
FROM
Cons_Columns
WHERE
Cons_Columns.Owner = Cons.R_Owner
AND Cons_Columns.Constraint_Name = Cons.R_Constraint_Name
|| ' ON DELETE ' || Delete_Rule
ELSE ''
END
|| ' ' || DEFERRABLE || ' ' || DEFERRED
|| ' ' || VALIDATED || ' ' || STATUS || RTRIM(' ' || RELY)
|| ';'
FROM
All_Constraints Cons
WHERE
Owner = 'SYS'
ORDER BY
1,
Constraint_Name;Shoblock, thanx!
For NUMBER is was using a wrong COLUMN, and also in the wrong order. Serves me right for not following the documentation. And, i just ignored FLOAT. But not it mostly matches DESC (except this query shows the ", 0" where DESC drop it instead).
I fixed the query above.
The XML part that gets the long has a failure. If the Data_Default contains an XML special char it will get encoded. The way to not encode it, it looks, requires PL/SQL. Which means it would not be done in one query (without a FUNCTION).
I am curious if anyone else is interested in such queries, whether for "fun" or otherwise.
Maybe you are looking for
-
I am using an iPad 2 and I can't find out how to use the optimum app with the apple tv mirroring function. Is there anyway to do this?
-
What is the index tab in Balance Sheet Revaluation for?
Hi All, Whenever I put a value in the Index tab in Balance Sheet Revaluation (Consumer Price Index), the revaluated amount in the Balance Sheet becomes the same as the local currency. No matter what amount I put in the Index tab, it is always the sam
-
How do you know or find out what the URL is on a calender published on .mac
I want to publish or subscribe several different calenders....how do you know or where do you find the url when you go to subscibe? thanks ron
-
Help with no os installed!
Hello! Recently I reset my macbook pro due to it running extremely slow. I did a full system wipe and lost all my files which is fine. But, I get prompted to a meny with several options: 1. Restore from time machine back up (Which I don't want) 2. Re
-
Is it possible do simultaneo​us input put and out on a PCI-6110 boar?
We are trying to send out a signal to a transducer, which in turn sends a signal to a hydrophone. Then recieve that signal that is coming in the hydrophone? Is this possible on a PCI-6110 DAQ board? or would we need two boards, the signal is a 50kilo