Extracting create table statements from a existing database. - sql

I'm trying to extract a create table statement from an existing derby schema. I can get all of the columns and data types via this.
select * from SYS.SYSTABLES a inner join sys.SYSCOLUMNS b on a.TABLEID= b.REFERENCEID
This gives me the table name, column name, data type, default value, auto increment etc. Very useful for basic table construction. It's lacking for constraints and indexes.
I can get some information on constraints via:
select a.*, b.TABLENAME from SYS.SYSCONSTRAINTS a inner join sys.SYSTABLES b on a.TABLEID = b.TABLEID
This will give me the constraint name, table it's on, and a type. I don't know what the type letters mean. I'm also not sure there's index information here.
What I would like is something very similar to what I can get from views.
select * from sys.SYSVIEWS
There's a column from that called VIEWDEFINITION that will give me the create statement for each view. That would be incredibly useful for tables.
Thanks,

The full source code for dblook is available as part of the Derby source. You can read about dblook here: http://db.apache.org/derby/docs/10.8/tools/ctoolsdblook.html

Related

JOIN of DB table and internal table produces "is not defined in the ABAP Dictionary"

First: I'm working on a existing code and want to add some new stuff to it and I'm really new to ABAP
My goal: I want to duplicate an existing table and remove all values that occur multiple times. That - at least I think - works. Afterwards I want to INNER JOIN this new created table with another already existing table, but unfortunately I always get the following error:
Method MethodName "newCreatedTable" is not defined in the ABAP Dictionary as a table, projection view, or database view
Additional Info: As you can see I'm working inside of a method!
Here is my code what I've done so far:
creating new table and delete all duplicates
DATA newCreatedTable TYPE STANDARD TABLE OF existingTable.
SELECT columnName
FROM existingTable INTO TABLE newCreatedTable.
DELETE ADJACENT DUPLICATES
FROM newCreatedTable COMPARING columnName.
here is where the error happens
SELECT *
FROM anotherExistingTable as p
INNER JOIN newCreatedTable as t on t~columnName = p~columnName
...
I hope someone can help me out in this case! Thank You in advance!
If I'm not wrong your code looks like this:
DATA newCreatedTable TYPE STANDARD TABLE OF existingTable.
SELECT columnName FROM existingTable INTO TABLE newCreatedTable.
DELETE ADJACENT DUPLICATES
FROM newCreatedTable COMPARING columnName.
SELECT *
FROM anotherExistingTable
INNER JOIN newCreatedTable as t on t~columnName = p~columnName
If this is the case then you cannot make a SELECT on an internal table. You can only make this operation on a table that exists in the ABAP dictionary.
Your code should look like this:
DATA newCreatedTable TYPE STANDARD TABLE OF existingTable.
SELECT columnName
FROM existingTable INTO TABLE #newCreatedTable.
DELETE ADJACENT DUPLICATES FROM newCreatedTable COMPARING columnName.
SELECT *
FROM anotherExistingTable
FOR ALL ENTRIES IN #newCreatedTable " <-------------- Use FOR ALL ENTRIES
WHERE columnName = #newCreatedTable-columnName. " <-- in your code

Inserting from one table or view into another but avoid combination duplicates- Can this be done in SQL? If so how?

I have a table that has a primary key WORKITEMID, and the following 3 foreign keys PRODSERVID,PROCESSID,and TASKKNOWID.
I have a view that I can create that also has PRODSERVID,PROCESSID, AND TASKKNOWID. This view will usually have ALL the records in above table plus some new ones - not in the table. The 'table' by definition is meant to hold the unique combinations of PRODSERVID, PROCESSID, and TASKKNOWID.
I would like to insert from the view into the table any new combinations in the view not present in the table. And I don't want to overwrite the existing WORKITEMIDs in the INSERT- because those WORKITEMIDs are used elsewhere.
Can this be done in SQL?
Thanks
Absolutely, the simplest form of criteria for this is to use the negation of EXISTS()
INSERT INTO [TableName] (PRODSERVID,PROCESSID,TASKKNOWID,... )
SELECT PRODSERVID,PROCESSID,TASKKNOWID,...
FROM [ViewName] v
WHERE NOT EXISTS (
SELECT 1 FROM [TableName] t
WHERE t.PRODSERVID = v.PRODSERVID AND t.PROCESSID = v.PROCESSID AND t.TASKKNOWID = v.TASKKNOWID
)
replace the ... with your other fields
You could also use a non-corellating outer join but I find not exists makes the intent much clearer.
There is a good comparison of the different approaches to this issue in this article: T-SQL commands performance comparison – NOT IN vs SQL NOT EXISTS vs SQL LEFT JOIN vs SQL EXCEPT

Most elegant way to create 'subrecord' type keeping names of columns

So I'm playing with Postgres' composite types, and I cannot figure out one thing. Suppose I want to use subset of columns of certain table, or mix of different columns of several different tables used in the query, and create a record type out of them.
Logically, simple (c.id, c.name) should work, but it seems that column names are actually lost - it's not possible to address fields of the records by name and id, and, for example, to_json function cannot use field names when creating json out of this record. Using subquery (select c.id, c.name) is predictably failing with subquery must return only one column error.
I can, of course, use lateral join or common table expression to create this sub-type, but I'm thinking - if there's more elegant way?
see db<>fiddle demo with table example and test query
create table test(id integer, name text, price int);
insert into test(id,name,price)
values
(1,'name1',1),
(2,'name2',12),
(3,'name3',23),
(5,'name5',4),
(9,'name9',3);
create type sub_test as (id integer, name text);
select
c.price,
-- using predefined type - works
to_json((c.id, c.name)::sub_test),
-- creating row type on the fly - doesn't work, names are lost
to_json((c.id, c.name)),
-- using derived table created with lateral join - works
to_json(d)
from test as c, lateral(select c.id, c.name) as d

SQL how to create and import only specific columns from table A to a new table, table B

In Table A i have many fields like referenceid, amount, timestamp, remarks, status, balancebefore, balanceafter, frmsisdn, tomsisdn, id etc etc
I want to create a new table, Table B based of Table A(with column names, datatypes etc etc) but i only need specific columns that are in table A.
I tried select * into TableB from TableA where 1 = 2 but it says ORA-00905: missing keyword. I am using TOAD.
thank you
In Oracle, the correct syntax is create table as. SELECT INTO is used primarily in SQL Server and Sybase.
create table tableb as
select . . .
from tableA;
Only include the where clause if you don't actually want to insert any rows.
In MySQL the syntax is the same as Oracle's (see here).
Notice that the new table does not contain any constraints from the original table (indexes, keys, etc.)

How to auto-redefine view when underlying table changes (new column)?

We've got a view that's defined like this
CREATE VIEW aView as
SELECT * from aTable Where <bunch of conditions>;
The "value" of the view is in the where-condition, so it is okay to use a Select * in this case.
When a new column is added to the underlying table, we have to redefine the view with a
CREATE OR REPLACE FORCE VIEW aView as
SELECT * from aTable Where <bunch of conditions>;
as the Select * seems to get "translated" into all the columns present at the time the view is (re-)defined.
My question: How can we avoid this extra step?
(If the answer is dependent on the RDBMS, we're using Oracle.)
I know you specified Oracle, but the behavior is the same in SQL Server.
One way to update the view with the new column is to use:
exec sp_refreshview MyViewName
go
Of course, I also agree with the other comments about not using a SELECT * in a view definition.
This extra step is mandatory in Oracle: you will have to recompile your view manually.
As you have noticed, the "*" is lost once you create a view:
SQL> create table t (id number);
Table created
SQL> create view v as select * from t;
View created
SQL> select text from user_views where view_name = 'V';
TEXT
-------------------------------------------------------
select "ID" from t
You should not be using * in your views. Specify the columns explicitly.
That way you are only retrieving the data you need, and thus avoid potential issues down the road where someone adds a column to a table that you do not want that view to return (e.g., a large binary column that would adversely impact performance).
Yes, you need to recompile the view to add another column, but this is the correct process. That way you avoid other compilation issues, such as if the view reference two tables, and someone adds a duplicate column name in one of the tables. The compiler would then have issues determining which of the columns was being referred to if you did not prefix a reference to the column with a table alias, or it might complain if there are duplicate column names in the results.
The problem with automatically updating views to add columns comes when you extend your model, for example to
SELECT a.*, std_name_format(a.first_name, a.middle_names, a.last_name) long_name
or even
SELECT a.*, b.* from table_a a join table_b b....
If you have a view of just SELECT * FROM table, then you probably should be using a synonym or addressing the table directly.
If the view is hiding rows (SELECT * FROM table WHERE...), then you can look at the feature variously known as Fine Grained Access Control (FGAC), Row Level Security (RLS) or Virtual Private Database (VPD).
You might be able to do something with a DDL trigger but that would get complicated.