From 995bb2499c90c3ca917c29d852634f047041f9fa Mon Sep 17 00:00:00 2001
From: Christopher Lenke <christopher.lenke@uni-bielefeld.de>
Date: Tue, 24 Sep 2024 21:49:05 +0200
Subject: [PATCH] 24.09.2024

---
 .../Table functions/set_autoincrement.txt     | 27 +++++++++++++++++++
 1 file changed, 27 insertions(+)
 create mode 100644 Basic tables/Table functions/set_autoincrement.txt

diff --git a/Basic tables/Table functions/set_autoincrement.txt b/Basic tables/Table functions/set_autoincrement.txt
new file mode 100644
index 0000000..fd03c7b
--- /dev/null
+++ b/Basic tables/Table functions/set_autoincrement.txt	
@@ -0,0 +1,27 @@
+-- DROP PROCEDURE basics.set_autoincrement(varchar, varchar);
+
+CREATE OR REPLACE PROCEDURE basics.set_autoincrement(table_name character varying, col_name character varying)
+ LANGUAGE plpgsql
+AS $procedure$
+
+-- sets autoincrement on existing table starting after max value if the column
+
+declare 
+
+max_col_value int;
+
+BEGIN
+
+EXECUTE format('select max(%s) from basics.%s', col_name, table_name) INTO max_col_value;
+max_col_value := max_col_value +1;
+
+execute 'drop SEQUENCE if exists basics.'||table_name ||'_'||col_name||'_seq cascade';
+execute 'CREATE SEQUENCE basics.'||table_name ||'_'||col_name||'_seq START WITH '||max_col_value ;
+execute 'ALTER TABLE basics.'||table_name ||' ALTER COLUMN '||col_name||' 
+SET DEFAULT nextval(''basics.'||table_name ||'_'||col_name||'_seq'')';
+commit;
+
+END;
+	
+$procedure$
+;
\ No newline at end of file
-- 
GitLab