I have to remove this constraint on the TYPE_FR column from an existing table but this one does not have a constraint name and the examples I find need the name of the constraint that this one does not have. Thank you
TYPE_FR INTEGER NOT NULL CHECK (TYPE_FR > 0 AND TYPE_FR < 3)
Db2 will generate an anonymous (system generated) name for the constraint if you don't explicitly name the constraint.
You can find the system generated name in the catalog tables/views.
For Db2-on-Linux/Unix/Windows, here is one way to do it, example below.
If your Db2-server is Db2-for-Z/OS, then use sysibm.syschecks2.checkname to find the constraint name to drop.
If your Db2-server is Db2-for-i (as/400), then use qsys2.syschkcst.constraint_name to find the constraint name to drop.
create table MY_TEST_TABLE (TYPE_FR INTEGER NOT NULL CHECK (TYPE_FR > 0 AND TYPE_FR < 3) )
DB20000I The SQL command completed successfully.
select constname from syscat.colchecks where tabschema='USER1' and tabname = 'MY_TEST_TABLE'
CONSTNAME
--------------------------------------------------------------------------------------------------------------------------------
SQL210205171553170
1 record(s) selected.
begin
declare constraint_name varchar(128);
declare my_sql varchar(1024);
set constraint_name = (select constname
from syscat.colchecks
where tabschema='USER1'
and tabname = 'MY_TEST_TABLE'
);
if constraint_name is not null then
set my_sql = 'alter table MY_TEST_TABLE drop constraint '||constraint_name ;
execute immediate my_sql ;
end if;
end
DB20000I The SQL command completed successfully.
select constname from syscat.colchecks where tabschema='USER1' and tabname = 'MY_TEST_TABLE'
CONSTNAME
--------------------------------------------------------------------------------------------------------------------------------
0 record(s) selected.
Related
I have a Firebird table like this:
CREATE TABLE events (
event VARCHAR(6) NOT NULL
CHECK (event IN ('deploy', 'revert', 'fail')),
change_id CHAR(40) NOT NULL,
change VARCHAR(512) NOT NULL
);
Now I need to add another value to the IN() list in the CHECK constraint. How do I do that?
Things I've tried so far:
Updating the value in RDB$TRIGGERS.RDB$TRIGGER_SOURCE:
UPDATE RDB$TRIGGERS
SET RDB$TRIGGER_SOURCE = 'CHECK (event IN (''deploy'', ''revert'', ''fail'', ''merge''))'
WHERE RDB$TRIGGER_SOURCE = 'CHECK (event IN (''deploy'', ''revert'', ''fail''))';
Does not seem to work, as the trigger is compiled in RDB$TRIGGERS.RDB$TRIGGER_BLR.
Creating a new table with a new check, copying the data over, dropping the old table and renaming the new table. However, it seems that one cannot rename a Firebird table, so I can't make the new table have the same name as the old one.
I suspect updating RDB$TRIGGERS is the way to go (idk!), if only I could get Firebird to recompile the code. But maybe there's a better way?
You need to drop and the re-create the check constraint.
As you didn't specify a name for your constraint, Firebird created one, so you first need to find that name:
select trim(cc.rdb$constraint_name), trg.rdb$trigger_source
from rdb$relation_constraints rc
join rdb$check_constraints cc on rc.rdb$constraint_name = cc.rdb$constraint_name
join rdb$triggers trg on cc.rdb$trigger_name = trg.rdb$trigger_name
where rc.rdb$relation_name = 'EVENTS'
and rc.rdb$constraint_type = 'CHECK'
and trg.rdb$trigger_type = 1;
I just added the trigger source for informational reasons.
Once you have the name, you can drop it, e.g.
alter table events drop constraint integ_27;
and then add the new constraint:
alter table events
add constraint check_event_type
CHECK (event IN ('deploy', 'revert', 'fail', 'merge'));
In the future you don't need to look for the constraint name because you already it.
Here's how to do it dynamically:
SET AUTOddl OFF;
SET TERM ^;
EXECUTE BLOCK AS
DECLARE trig VARCHAR(64);
BEGIN
SELECT TRIM(cc.rdb$constraint_name)
FROM rdb$relation_constraints rc
JOIN rdb$check_constraints cc ON rc.rdb$constraint_name = cc.rdb$constraint_name
JOIN rdb$triggers trg ON cc.rdb$trigger_name = trg.rdb$trigger_name
WHERE rc.rdb$relation_name = 'EVENTS'
AND rc.rdb$constraint_type = 'CHECK'
AND trg.rdb$trigger_type = 1
INTO trig;
EXECUTE STATEMENT 'ALTER TABLE EVENTS DROP CONSTRAINT ' || trig;
END^
SET TERM ;^
COMMIT;
ALTER TABLE events ADD CONSTRAINT check_event_type CHECK (
event IN ('deploy', 'revert', 'fail', 'merge')
);
COMMIT;
I had to disable AUTOddl and put in explicit commits or else I got a deadlock on the ALTER TABLE ADD CONSTRAINT statement.
Here's how to do it dynamically:
EXECUTE BLOCK RETURNS (STMT VARCHAR(1000)) AS
BEGIN
SELECT TRIM(R.RDB$CONSTRAINT_NAME)
FROM RDB$RELATION_CONSTRAINTS R
WHERE R.RDB$RELATION_NAME = 'TABLE_NAME'
AND UPPER(R.RDB$CONSTRAINT_TYPE) = UPPER('PRIMARY KEY')
INTO :STMT;
IF (:STMT IS NOT NULL) THEN
BEGIN
EXECUTE STATEMENT 'ALTER TABLE TABLE_NAME DROP CONSTRAINT ' || :STMT || ';';
EXECUTE STATEMENT 'ALTER TABLE TABLE_NAME ADD CONSTRAINT ' || :STMT || ' PRIMARY KEY (FIELD1, FIELD2, FIELD3);';
END
ELSE
BEGIN
EXECUTE STATEMENT 'ALTER TABLE FIELD1 ADD CONSTRAINT PK_PRIMARY_NAME PRIMARY KEY (FIELD1, FIELD2, FIELD3);';
END
END;
I am autogenerated SQL queries based on some condition of the autogenerated resulted into this query
DO
$$
BEGIN
IF NOT EXISTS (SELECT FROM pg_attribute
WHERE attrelid = 'public.registration'::regclass -- table name here
AND attname = 'price' -- column name here
AND NOT attisdropped
) THEN
ALTER TABLE public.registration
ADD COLUMN price text UNIQUE NULL;
ELSE
ALTER TABLE public.registration
ALTER COLUMN price TYPE text,
ADD CONSTRAINT IF NOT EXISTS registration_price_key UNIQUE (price);
END IF;
END
$$
So the table is is already there by if the column is not there it will be added and a unique constraint will be added to that column problem if it does not already exist
I get that an syntax error on this line `near NOT
ADD CONSTRAINT IF NOT EXISTS registration_price_key UNIQUE (price);
but why?
the issue:
i need to do something like this
drop table if exists tt_t;
create temp table tt_t(id serial primary key, main_id int, external_id int);
insert into tt_t(main_id, external_id)
select currval(pg_get_serial_sequence('tt_t', 'id')), 1
where not exists (select from tt_t where external_id = 1);
but execution raises an error
SQL Error [55000]: ERROR: currval of sequence "tt_t_id_seq" is not yet defined in this session
solution:
there is a way to solve this with anonymous code block
do
$$
begin
if not exists(select from tt_t where external_id = 1)
then
insert into tt_t(external_id, main_id)
values(1, currval(pg_get_serial_sequence('tt_t', 'id')));
end if;
end;
$$
;
but anonymous blocks has some restrictions e.g. Dapper parameters not working with PostgreSQL through npgsql connection, is postgres anonymous function parameterization supported?
how do i fix it without anonymous code block (UPD: and without any DDL changes)?
probable solution:
insert into tt_t(id, main_id, external_id)
select nextval(pg_get_serial_sequence('tt_t', 'id')), currval(pg_get_serial_sequence('tt_t', 'id')), 1
where not exists (select from tt_t where external_id = 1);
shorter code has been proposed to me
insert into tt_t(id, main_id, external_id)
select nextval(pg_get_serial_sequence('tt_t', 'id')), lastval(), 1
where not exists (select from tt_t where external_id = 1);
but i'm not sure if nextval will be calculated first
What about using a default value:
drop table if exists tt_t;
create temp table tt_t(id serial primary key, main_id int default lastval(), external_id int);
insert into tt_t(external_id)
select 1
where not exists (select * from tt_t where external_id = 1);
In theory it shouldn't be possible that another nextval() is called between the one for the id and the lastval(). However I am not 100% sure if there are some corner cases that I don't know of.
The following works as well (even if one or more of the external_id values already exist).
insert into tt_t(external_id)
select *
from (values (1),(2),(3)) x (external_id)
where not exists (select *
from tt_t
where external_id = x.external_id);
I am writing migration script to migrate database. I have to duplicate the row by incrementing primary key considering that different database can have n number of different columns in the table. I can't write each and every column in query. If i simply just copy the row then, I am getting duplicate key error.
Query: INSERT INTO table_name SELECT * FROM table_name WHERE id=255;
ERROR: duplicate key value violates unique constraint "table_name_pkey"
DETAIL: Key (id)=(255) already exist
Here, It's good that I don't have to mention all column names. I can select all columns by giving *. But, same time I am also getting duplicate key error.
What's the solution of this problem? Any help would be appreciated. Thanks in advance.
If you are willing to type all column names, you may write
INSERT INTO table_name (
pri_key
,col2
,col3
)
SELECT (
SELECT MAX(pri_key) + 1
FROM table_name
)
,col2
,col3
FROM table_name
WHERE id = 255;
Other option (without typing all columns , but you know the primary key ) is to CREATE a temp table, update it and re-insert within a transaction.
BEGIN;
CREATE TEMP TABLE temp_tab ON COMMIT DROP AS SELECT * FROM table_name WHERE id=255;
UPDATE temp_tab SET pri_key_col = ( select MAX(pri_key_col) + 1 FROM table_name );
INSERT INTO table_name select * FROM temp_tab;
COMMIT;
This is just a DO block but you could create a function that takes things like the table name etc as parameters.
Setup:
CREATE TABLE public.t1 (a TEXT, b TEXT, c TEXT, id SERIAL PRIMARY KEY, e TEXT, f TEXT);
INSERT INTO public.t1 (e) VALUES ('x'), ('y'), ('z');
Code to duplicate values without the primary key column:
DO $$
DECLARE
_table_schema TEXT := 'public';
_table_name TEXT := 't1';
_pk_column_name TEXT := 'id';
_columns TEXT;
BEGIN
SELECT STRING_AGG(column_name, ',')
INTO _columns
FROM information_schema.columns
WHERE table_name = _table_name
AND table_schema = _table_schema
AND column_name <> _pk_column_name;
EXECUTE FORMAT('INSERT INTO %1$s.%2$s (%3$s) SELECT %3$s FROM %1$s.%2$s', _table_schema, _table_name, _columns);
END $$
The query it creates and runs is: INSERT INTO public.t1 (a,b,c,e,f) SELECT a,b,c,e,f FROM public.t1. It's selected all the columns apart from the PK one. You could put this code in a function and use it for any table you wanted, or just use it like this and edit it for whatever table.
is it possible to ALTER a PRIMARY KEY CLUSTERED Index on an existing table without losing the data?
If so, what is the ALTER command for this please?
EDIT
I want to add an additional column to the PRIMARY KEY CLUSTERED Index
Thanks
Here is what I've done in the past to change a primary key on a table:
BEGIN TRANSACTION doStuff
DECLARE #isValid bit
SET #isValid = 1
DECLARE #pkName varchar(50)
SET #pkName = (
SELECT TOP 1 name
FROM sys.key_constraints
WHERE type ='pk'
AND OBJECT_NAME(parent_object_id) = N'TableName'
)
DECLARE #sql nvarchar(2000)
SET #sql = N'
ALTER TABLE dbo.TableName
DROP CONSTRAINT ' + #pkName
EXEC (#sql)
IF (##ERROR <> 0)
BEGIN
PRINT 'Error deleting primary key'
SET #isValid = 0
END
ALTER TABLE dbo.TableName
ADD PRIMARY KEY (primary key columns separated by comma)
IF (##ERROR <> 0)
BEGIN
PRINT 'Error creating primary key'
SET #isValid = 0
END
IF (#isValid = 1)
BEGIN
PRINT 'Commit'
COMMIT TRANSACTION doStuff
END
ELSE
BEGIN
PRINT 'Rollback'
ROLLBACK TRANSACTION doStuff
END
Note as pointed out in: Best way to change clustered index (PK) in SQL 2005 this will reorder the data in your table throughout the operation, so depending on the size of the table it could take a significant amount of time.