I have a table on snowflake which has more than 100 columns, and I would like to add a suffix '_LA' to all the column names. Is there any easy way to do this in sql?
this script produce alter command for all columns of given schema.table name:
select 'ALTER TABLE ' || table_schema || '.' || table_name || ' RENAME COLUMN ' || column_name || ' TO _LA' || column_name
from information_schema.columns
where table_schema ilike 'schema' -- put your schema name here
and table_name ilike 'table' -- put your table name here
order by ordinal_position;
Related
I am trying to create a view by joining two tables. These two tables have a few columns with the same name. Which gives an error
SQL Error [42701]: ERROR: column "column_name" specified more than once
I cannot use column names while creating the view as there are 30+ columns and new columns will be added to both tables over the period of time. Hence, I have to use * to get all the columns.
Now, to eliminate columns which exist in both the table, I went ahead and did this:
SELECT 'SELECT ' || STRING_AGG('u2.' || column_name, ', ') || ' FROM schema_name.table_name u2'
FROM information_schema.columns
WHERE table_name = 'table_name'
AND table_schema = 'schema_name'
AND column_name NOT IN ('column_name');
This gives me the query to select data from schema_name.table_name without the column column_name. Great!!
The problem: How do I execute the result of the above query?
I tried PREPARE statement, it is just executing the above query and not the result of the above query.
Also, creating a temporary table with no column "column_name" isn't a viable solution.
You need to prepare a dynamic query and then EXECUTE it. It would be something like this:
DO
$do$
BEGIN
EXECUTE (
SELECT CONCAT('CREATE VIEW temp_view AS SELECT ',
-- SELECT table1 columns here
(SELECT STRING_AGG('u1.' || column_name, ', ')
FROM information_schema.columns
WHERE table_name = 'table1'
AND table_schema = 'schema_name'
-- AND column_name NOT IN ('column_name') -- not omitting for table1
),
', ',
-- SELECT table2 columns here
(SELECT STRING_AGG('u2.' || column_name, ', ')
FROM information_schema.columns
WHERE table_name = 'table2'
AND table_schema = 'schema_name'
AND column_name NOT IN ('column_name')),
-- Dynamically prepare the FROM and JOIN clauses
' FROM table1 u1 JOIN table2 u2 ON u1.id = u2.table1_id'));
END
$do$;
CHECK DEMO
I need a query to count the total number of non-null values for each column in a table. Since my table has hundreds of columns I'm looking for a solution that only requires me to input the table name.
Perhaps using the result of:
select COLUMN_NAME from ALL_TAB_COLUMNS where TABLE_NAME='ORDERS';
to get the column names and then a subquery to put counts against each column name? The additional complication is that I only have read-only access to the DB so I can't create any temp tables.
Slightly out of my league with this one so any help is appreciated.
Construct the query in SQL or using a spreadsheet. Then run the query.
For instance, assuming that your column names are simple and don't have special characters:
select replace('select ''[col]'', count([col]) from orders union all ',
'[col]', COLUMN_NAME
) as sql
from ALL_TAB_COLUMNS
where TABLE_NAME = 'ORDERS';
(Of course, this can be adapted for more complex column names, but I'm trying to show the idea.)
Then copy the code, remove the final union all and run it.
You can put this in one string if there are not too many columns:
select listagg(replace('select ''[col]'', count([col]) from orders',
'[col]', COLUMN_NAME
), ' union all '
) within group (order by column_name) as sql
from ALL_TAB_COLUMNS
where TABLE_NAME = 'ORDERS';
You can also use execute immediate using the same query, but that seems like overkill.
If you're happy with the results row-ar rather than column-ar:
SELECT 'SELECT ''dummy'', 0 FROM DUAL' FROM DUAL
UNION ALL
SELECT
' UNION ALL SELECT ''' ||
column_name ||
''', COUNT(' ||
column_name ||
') FROM ' ||
TABLE_NAME
FROM
all_tab_columns
WHERE
table_name = 'ORDERS'
This is an "SQL that writes an SQL" that you can then copy and run to get your answers. Should make a resultset that looks like:
SELECT 'dummy', 0 FROM dual
UNION ALL SELECT 'col1', COUNT(col1) FROM ORDERS
UNION ALL SELECT 'col2', COUNT(col2) FROM ORDERS
...
If you want your results column-ar:
SELECT 'SELECT '
UNION ALL
SELECT
'COUNT(' ||
column_name ||
') as count_' ||
column_name ||
', ' ||
TABLE_NAME
FROM
all_tab_columns
WHERE
table_name = 'ORDERS'
UNION ALL
SELECT 'null as dummy_column FROM ORDERS'
Should make a resultset that looks like:
SELECT
COUNT(col1) as count_col1,
COUNT(col2) as count_col2,
...
null as dummycoll FROM orders
Caveat: I don't have oracle installed anywhere I can test these, it's written from memory and may need some debugging
This will generate the SQL to get the counts in columns and will handle case sensitive column names and column names with non-alpha-numeric characters:
SELECT 'SELECT '
|| LISTAGG(
'COUNT("' || column_name || '") AS "' || column_name || '"',
', '
) WITHIN GROUP ( ORDER BY column_id )
|| ' FROM "' || table_name || '"' AS sql
FROM ALL_TAB_COLUMNS
WHERE TABLE_NAME = 'ORDERS'
GROUP BY TABLE_NAME;
or, if you have a large number of columns that is generating a string longer than 4000 characters you can use a custom aggregation function to aggregate VARCHAR2s into a CLOB and then do:
SELECT 'SELECT '
|| CLOBAgg( 'COUNT("' || column_name || '") AS "' || column_name || '"' )
|| ' FROM "' || table_name || '"' AS sql
FROM ALL_TAB_COLUMNS
WHERE TABLE_NAME = 'ORDERS'
GROUP BY TABLE_NAME;
In Oracle 19 (I used similar code in Ora 12, maybe that works too), this works without generating another select to execute:
select * from
(
select table_name, column_name,
to_number( extractvalue( xmltype(dbms_xmlgen.getxml('select count(to_char(substr('||column_name||',1,1))) c from '||table_name)) ,'/ROWSET/ROW/C')) count
from all_tab_columns where owner = user
)
--where table_name = 'MY_TABLE'
;
It will create XML with count, from which it extracts the current count. The substr and to_char functions here are used to extract first character, so it will works with CLOB columns also
I want to rename many constraints (PK, FK, ...etc. ) that have default names which start with 'SYS' to be able to insert the same data in other DB.
I found the following script that I changed to get what I want:
BEGIN
FOR cn IN (
SELECT constraint_name
FROM user_constraints
WHERE constraint_type = 'P'
AND table_name = 'SPECIALITE'
)
LOOP
EXECUTE IMMEDIATE 'ALTER TABLE ' || cn.table_name || ' RENAME CONSTRAINT ' || cn.constraint_name || ' TO PK_' || 'SPECIALITE';
END LOOP;
END;
This script works, but it seems a bit complicated for me, I wonder if it exists something like:
ALTER TABLE 'SPECIALITE' RENAME CONSTRANT (....)
The problem is I don't know the name of constraints, they have a default name, I know only tables where they are.
Is it possible?
As you already know, you need to run two queries.
select constraint_name from user_constraints
where table_name = <table_name> and constraint_type = 'P';
and with the constraint name in hand,
alter table <table_name> rename constraint <old_constr_name> to <new_constr_name>;
This will require copying the constraint name from the first query and pasting it into the second, in the proper place (<old_constr_name>).
If this was all, I wouldn't post an answer. But I remember something I read on AskTom some time ago - a clever way to avoid copying and pasting, using the COLUMN command in SQL*Plus. (This may also work in SQL Developer and Toad.) Something like this:
column constraint_name new_val c -- Note: no semicolon - this is SQL*Plus, not SQL
select constraint_name from user_constraints
where table_name = <table_name> and constraint_type = 'P';
alter table <table_name> rename constraint &c to <new_constr_name>;
If you need to change many PK constraint names, this will save some work. The constraint name returned by the SELECT query is saved in the "new_val" labeled "c" from the SQL*Plus COLUMN command, and it is used in the ALTER TABLE statement.
Add user_cons_columns view to your SQL so you can generate constraint names. Here is a quick and dirty example:
select 'ALTER TABLE ' || c.table_name || ' RENAME CONSTRAINT ' || c.constraint_name || ' TO ' || substr(c.constraint_type || '_' || c.table_name || '_' || replace(wm_concat(cc.column_name), ',', '_'), 0, 30) || ';'
from user_constraints c
join user_cons_columns cc on c.table_name = cc.table_name and c.constraint_name = cc.constraint_name
where c.constraint_name like 'SYS%'
group by c.table_name, c.constraint_name, c.constraint_type;
This SQL generates an executable script with commands like this:
ALTER TABLE TABLENAME RENAME CONSTRAINT SYS_xxxxxx TO C_TABLENAME_COLUMN;
Please note that I'm using undocumented wm_concat function. If you're using Oracle >= 11g consider using listagg instead.
If you don't have the constraint name, you can't do it directly. But you can easily generate the statement.
select 'ALTER TABLE ' || table_name || ' RENAME CONSTRAINT ' || constraint_name || ' TO PK_' || upper( table_name )
from user_constraints
where constraint_type = 'P'
and constraint_name like 'SYS%';
This select will list all tables with a constraint on its primary key that start by 'SYS'and rename it to PK_TABLE_NAME;
You just have to check if all statements looks ok for you and run them.
You also can use the generated column like this
select 'ALTER TABLE ' || table_name || ' RENAME CONSTRAINT ' || constraint_name || ' TO PK_' || upper( table_name )
from user_constraints
where constraint_type = 'P'
and generated = 'GENERATED NAME';
but you will have BIN tables and maybe other unwanted tables
I know that I can comment a column with COMMENT ON COLUMN table.column IS 'commentString', but is there a way to add the same comment to more than one column in one statement?
For example, I need to add the comment "User Data" to columns NAME and BIRTHDATE and I'd like to understand if it's possible to do it in one statement, instead of repeating COMMENT ON COLUMN x.y IS 'User Data' two times.
It is impossible in straight way, but you can do it with dynamic SQL in PL\SQL block
BEGIN
FOR i IN (SELECT t.owner || '.' || t.table_name || '.' || t.column_name col
FROM all_tab_cols t
WHERE t.owner = 'OWNER' AND t.table_name = 'TABLE_NAME' AND
t.column_name IN ('COL1', 'COL2'))
LOOP
EXECUTE IMMEDIATE 'COMMENT ON COLUMN ' || i.col ||
' IS ''PLACE COMMENT HERE''';
END LOOP;
END;
I need to update a column matching a specific pattern in all tables in an oracle database.
For example I have in all tables this column *_CID with is a foreign key to master table witch has a primary key CID
Thanks
You can use the naming convention and query all_tab_columns
declare
cursor c is
select table_owner , column_name, table_name from all_tab_columns where column_name like '%_CID';
begin
for x in c loop
execute immediate 'update ' || x.table_owner || '.' || x.table_name ||' set ' || x.column_name||' = 0';
end loop;
end;
If you have valid Fk's you can also use all_tab_constraints the fetch enabled FK's for your main table and fetch the columns name of the r_constraint_name.
I found a solution to my question:
BEGIN
FOR x IN (SELECT owner, table_name, column_name FROM all_tab_columns) LOOP
EXECUTE IMMEDIATE 'update ' || x.owner || '.' || x.table_name ||' set ' || x.column_name||' = 0 where '||x.column_name||' = 1';
END LOOP;
END;
thanks