Skip to content

Instantly share code, notes, and snippets.

@phpdave
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save phpdave/f64f6a80eca370eb3aeb to your computer and use it in GitHub Desktop.

Select an option

Save phpdave/f64f6a80eca370eb3aeb to your computer and use it in GitHub Desktop.
Retreive the Primary key constraints columns by table name. #IBMi #DB2fori #SQL Thanks for Scott F. for the example code
WITH xx (CST_NAME, CST_COL_CNT, CST_SCHEMA, CST_TABLE) AS
(
SELECT CONSTRAINT_NAME, CONSTRAINT_KEYS, CONSTRAINT_SCHEMA, TABLE_NAME FROM QSYS2.SYSCST A
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME='MYTABLE'
)
SELECT CONSTRAINT_SCHEMA, TABLE_NAME, CONSTRAINT_NAME, COLUMN_NAME FROM QSYS2.SYSCSTCOL, xx where
xx.CST_SCHEMA = CONSTRAINT_SCHEMA AND
xx.CST_TABLE = TABLE_NAME AND
xx.CST_NAME = CONSTRAINT_NAME
/* Creating table LIBRARY.MYTABLE */
/* ::NOTE:: PRIMARY KEY (ID) - sets our primary key constraint to the autogenerated ID field*/
CREATE TABLE LIBRARY.MYTABLE (
ID BIGINT GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1, NO ORDER, NO CYCLE, NO MINVALUE, NO MAXVALUE, CACHE 20) NOT HIDDEN ,
FIRSTNAME CHARACTER (30) NOT HIDDEN ,
LASTNAME CHARACTER (50) NOT HIDDEN ,
PRIMARY KEY (ID) ) NOT VOLATILE ;
/* Setting column labels for LIBRARY.MYTABLE */
LABEL ON COLUMN LIBRARY.MYTABLE ( ID TEXT IS 'Record ID for SQL purposes' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment