Is there a way to alter many tables to add default values to a common column name? - sql

We have a set of 45 tables which carry a common column {variety}.
The need is to set all such columns with a default value {comedy}.
The ALTER TABLE (SCHEMA.TABLE_NAME) MODIFY(VARIETY DEFAULT 'COMEDY')
Will get it done, but I am wondering if there is a way to create a sql script in Oracle 11g that will change all tables within the schema which have a common coloumn name to the common default value.

DECLARE
cnt NUMBER;
BEGIN
FOR x IN (
SELECT DISTINCT t.table_name
FROM user_tables t
INNER JOIN user_tab_columns c ON c.table_name = t.table_name
) LOOP
EXECUTE IMMEDIATE 'ALTER TABLE (SCHEMA.' || x.table_name || ') MODIFY(VARIETY DEFAULT ''COMEDY'')';
END LOOP;
END;

The alter table statement can be written as following,
using alternate quoting mechanism.
'alter table ' || x.table_name || q'[ modify (variety default 'COMEDY')]'

Related

How to drop all not null constraints from a DB2 table

I would like to drop all not null constraints from all columns in a table in DB2 without having to specify each column name.
Ideally this would be a function, where I could pass a table name as a parameter. Going through sysibm.syscolumns to get the not null columns is perfectly fine.
Thanks!
EDIT:
A bit of background:
DB: DB2 LUW v11.1.0.0
OS: Linux, Debian (Debian 4.9.51-1 (2017-09-28)
I am creating a table from another table and need to import data into the newly created table. Unfortunately, the data to be imported sometimes does not have all the values which are needed for the not null columns, hence I have to remove all not null constraints before loading the data.
For Oracle, I have the following:
function f_remove_mandatory(p_tbname in varchar2) return boolean is
l_tbname all_tab_columns.table_name%type;
l_AltTabTxt varchar2(220);
cursor c_AlterDlTab (p_tablename in varchar2) IS
select column_name
from user_tab_columns
where table_name = p_tablename
and nvl(nullable,'x') = 'N';
begin
l_tbname := UPPER(p_tbname);
for c1 in c_AlterDlTab (l_tbname) loop
execute immediate 'ALTER TABLE ' || l_tbname ||' MODIFY ' || c1.column_name || ' NULL';
end loop;
return true;
exception when others then return false;
end;
And need something similar for DB2.

Get max(length(column)) for all columns in an Oracle table

I need to get the maximum length of data per each column in a bunch of tables. I'm okay with doing each table individually but I'm looking for a way to loop through all the columns in a table at least.
I'm currently using the below query to get max of each column-
select max(length(exampleColumnName))
from exampleSchema.exampleTableName;
I'm basically replacing the exampleColumnName with each column in a table.
I've already went through 3-4 threads but none of them were working for me either because they weren't for Oracle or they had more details that I required (and I couldn't pick the part I needed).
I'd prefer to have it in SQL than in PLSQL as I don't have any create privileges and won't be able to create any PLSQL objects.
Got the below query to work -
DECLARE
max_length INTEGER; --Declare a variable to store max length in.
v_owner VARCHAR2(255) :='exampleSchema'; -- Type the owner of the tables you are looking at
BEGIN
-- loop through column names in all_tab_columns for a given table
FOR t IN (SELECT table_name, column_name FROM all_tab_cols where owner=v_owner and table_name = 'exampleTableName') LOOP
EXECUTE IMMEDIATE
-- store maximum length of each looped column in max_length variable
'select nvl(max(length('||t.column_name||')),0) FROM '||t.table_name
INTO max_length;
IF max_length >= 0 THEN -- this isn't really necessary but just to ignore empty columns. nvl might work as well
dbms_output.put_line( t.table_name ||' '||t.column_name||' '||max_length ); --print the tableName, columnName and max length
END IF;
END LOOP;
END;
Do let me know if the comments explain it sufficiently, else I'll try to do better. Removing table_name = 'exampleTableName' might loop for all tables as well, but this is okay for me right now.
You can try this; although it uses PL/SQL it will work from within SQL-Plus. It doesn't loop. Hopefully you don't have so many columns that the SELECT query can't fit in 32,767 characters!
SET SERVEROUTPUT ON
DECLARE
v_sql VARCHAR2(32767);
v_result NUMBER;
BEGIN
SELECT 'SELECT GREATEST(' || column_list || ') FROM ' || table_name
INTO v_sql
FROM (
SELECT table_name, LISTAGG('MAX(LENGTH(' || column_name || '))', ',') WITHIN GROUP (ORDER BY NULL) AS column_list
FROM all_tab_columns
WHERE owner = 'EXAMPLE_SCHEMA'
AND table_name = 'EXAMPLE_TABLE'
GROUP BY table_name
);
EXECUTE IMMEDIATE v_sql INTO v_result;
DBMS_OUTPUT.PUT_LINE(v_result);
END;
/

drop all tables sharing the same prefix in postgres

I would like to delete all tables sharing the same prefix ('supenh_agk') from the same database, using one sql command/query.
To do this in one command you need dynamic SQL with EXECUTE in a DO statement (or function):
DO
$do$
DECLARE
_tbl text;
BEGIN
FOR _tbl IN
SELECT quote_ident(table_schema) || '.'
|| quote_ident(table_name) -- escape identifier and schema-qualify!
FROM information_schema.tables
WHERE table_name LIKE 'prefix' || '%' -- your table name prefix
AND table_schema NOT LIKE 'pg\_%' -- exclude system schemas
LOOP
RAISE NOTICE '%',
-- EXECUTE
'DROP TABLE ' || _tbl; -- see below
END LOOP;
END
$do$;
This includes tables from all schemas the current user has access to. I excluded system schemas for safety.
If you do not escape identifiers properly the code fails for any non-standard identifier that requires double-quoting.
Plus, you run the risk of allowing SQL injection. All user input must be sanitized in dynamic code - that includes identifiers potentially provided by users.
Potentially hazardous! All those tables are dropped for good. I built in a safety. Inspect the generated statements before you actually execute: comment RAISE and uncomment the EXECUTE.
If any other objects (like views etc.) depend on a table you get an informative error message instead, which cancels the whole transaction. If you are confident that all dependents can die, too, append CASCADE:
'DROP TABLE ' || _tbl || ' CASCADE;
Closely related:
Update column in multiple tables
Changing all zeros (if any) across all columns (in a table) to... say 1
Alternatively you could build on the catalog table pg_class, which also provides the oid of the table and is faster:
...
FOR _tbl IN
SELECT c.oid::regclass::text -- escape identifier and schema-qualify!
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname NOT LIKE 'pg\_%' -- exclude system schemas
AND c.relname LIKE 'prefix' || '%' -- your table name prefix
AND c.relkind = 'r' -- only tables
...
System catalog or information schema?
How to check if a table exists in a given schema
How does c.oid::regclass defend against SQL injection?
Table name as a PostgreSQL function parameter
Or do it all in a single DROP command. Should be a bit more efficient:
DO
$do$
BEGIN
RAISE NOTICE '%', (
-- EXECUTE (
SELECT 'DROP TABLE ' || string_agg(format('%I.%I', schemaname, tablename), ', ')
-- || ' CASCADE' -- optional
FROM pg_catalog.pg_tables t
WHERE schemaname NOT LIKE 'pg\_%' -- exclude system schemas
AND tablename LIKE 'prefix' || '%' -- your table name prefix
);
END
$do$;
Related:
Is there a postgres command to list/drop all materialized views?
Using the conveniently fitting system catalog pg_tables in the last example. And format() for convenience. See:
How to check if a table exists in a given schema
Table name as a PostgreSQL function parameter
Suppose the prefix is 'sales_'
Step 1: Get all the table names with that prefix
SELECT table_name
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'sales_%';
Step 2: Click the "Download as CSV" button.
Step 3: Open the file in an editor and replace "sales_ with ,sales
and " with a space
Step 4: DROP TABLE sales_regist, sales_name, sales_info, sales_somthing;
This is sql server command, can you try this one, is it worked in postgres or not.
This query wil generate the sql script for delete
SELECT 'DROP TABLE "' || TABLE_NAME || '"'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '[prefix]%'
[EDIT]
begin
for arow in
SELECT 'DROP TABLE "' || TABLE_NAME || '"' as col1
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '[prefix]%'
LOOP
--RAISE NOTICE '%',
EXECUTE 'DROP TABLE ' || arow ;
END LOOP;
end;

Truncating table before dynamic SQL with looping variables inside of one function

I have a function that loops through specific schema names and inserts data into a table. I would like to be able to truncate said table before the insert loop occurs. I've tried putting the truncate statement inside of the dynamic query and that caused it to only keep schema's data inside of the table. I also tried declaring it as it's own variable and then executing the statement separately from the looping statement -- but that resulted in the same.
So my question is -- Where exactly would I put a truncate table dwh.prod_table_notify statement within this function? So that every time I run this function the table would be truncated and then the insert would properly loop through each schema being returned from the FOR statement.
NOTE: I'm forced to use postgres 8.2
CREATE OR REPLACE FUNCTION dwh.dim_table_notification()
RETURNS void
LANGUAGE plpgsql
AS $function$
Declare
myschema varchar;
sql2 text;
Begin
for myschema in
select distinct table_schema
from information_schema.tables
where table_name in ('dim_loan_type', 'dim_acct_type')
and table_schema NOT LIKE 'pg_%'
and table_schema NOT IN ('information_schema', 'ad_delivery', 'dwh', 'users', 'wand', 'ttd')
order by table_schema
loop
sql2 ='insert into dwh.prod_table_notify
select '''|| myschema ||''' as userid, loan_type_id as acct_type_id, loan_type::varchar(10) as acct_type, loan_type_desc::varchar(50) as acct_type_desc, term_code, 1 as loan_type from '|| myschema || '.' ||'dim_loan_type where term_code is null
union
select '''|| myschema ||''' as userid, acct_type_id, acct_type::varchar(10), acct_type_desc::varchar(50), term_code, 0 as loan_type from '|| myschema || '.' ||'dim_acct_type where term_code is null';
execute sql2;
end loop;
END;
$function$
CREATE OR REPLACE FUNCTION dwh.dim_table_notification()
RETURNS void LANGUAGE plpgsql AS
$func$
DECLARE
myschema text;
BEGIN
-- truncate simply goes here:
TRUNCATE dwh.prod_table_notify;
FOR myschema IN
SELECT quote_ident(table_schema)
FROM information_schema.tables
WHERE table_name IN ('dim_loan_type', 'dim_acct_type')
AND table_schema NOT LIKE 'pg_%'
AND table_schema NOT IN
('information_schema', 'ad_delivery', 'dwh', 'users', 'wand', 'ttd')
ORDER BY table_schema
LOOP
EXECUTE '
INSERT INTO dwh.prod_table_notify
(userid, acct_type_id, acct_type, acct_type_desc, loan_type)
SELECT '''|| myschema ||''', loan_type_id, loan_type::varchar(10)
, loan_type_desc::varchar(50), term_code, 1 AS loan_type
FROM '|| myschema || '.dim_loan_type
WHERE term_code IS NULL
UNION ALL
SELECT '''|| myschema ||''' AS userid, acct_type_id, acct_type::varchar(10)
, acct_type_desc::varchar(50), term_code, 0 AS loan_type
FROM '|| myschema || '.dim_acct_type
WHERE term_code IS NULL';
END LOOP;
END
$func$
Are you sure, you can actually use TRUNCATE? Quoting the manual for 8.2:
TRUNCATE cannot be used on a table that has foreign-key references from other tables, unless all such tables are also truncated in the same command.
If tables are small, DELETE is faster than TRUNCATE to begin with:
DELETE FROM dwh.prod_table_notify;
You have to sanitize identifiers! Use quote_ident(), also available in pg 8.2.
No point in using DISTINCT here.
Provide a column definition list for your INSERT. Else it can break in confusing ways, when you change the table later.
If rows in the two legs of the SELECT are unique, use UNION ALL instead of UNION. No point in trying to fold duplicates.

constraint on all numerical tables

I need to put a constraint on all numerical columns, this is what I tried:
Everything has to be possitive
ALTER TABLE * ADD CONSTRAINT Checknumbers CHECK ( > 0 )
This isn't working but I can't find a solution for it.
Is their any other syntax that I can use or do I need to do it manualy for each table?
You would need to create a separate constraint for each column in each table. You could potentially write a bit of dynamic SQL for this
DECLARE
l_sql_stmt VARCHAR2(1000);
BEGIN
FOR x IN (SELECT *
FROM user_tab_columns
WHERE data_type = 'NUMBER'
AND table_name in (SELECT table_name
FROM user_tables
WHERE dropped = 'NO' )
LOOP
l_sql_stmt := 'ALTER TABLE ' || x.table_name ||
' ADD CONSTRAINT chk_' || x.table_name || '_' || x.column_name ||
' CHECK( ' || x.column_name || ' > 0)';
EXECUTE IMMEDIATE l_sql_stmt;
END LOOP;
END;
For every numeric column in every table in the current schema, this will attempt to create a check constraint. The constraint name is limited to 30 characters so if the sum of the length of the table name and the column name is more than 25, this will attempt to generate an invalid identifier. You'd need to figure out an alternate way of generating the constraint name (or you could let the system generate a name). This also won't handle case-sensitive identifiers if you happen to have any of those. You'd need to double-quote the identifiers if that is an issue for you.