How to get primay priority restriction name from sql server using java

Suppose in the following table I want to get the primary key constraint name, which uapplication_pkey

CREATE TABLE application
(
  applicationid integer NOT NULL,
  screatedby character varying(255),
  screatedon timestamp without time zone,
  sfwversion integer,
  smodifiedby timestamp without time zone,
  smodifiedon character varying(255),
  stenantid character varying(255),
  CONSTRAINT uapplication_pkey PRIMARY KEY (applicationid)
)

I got help from this How to get the exact name of a constraint from a SQLException

But unable to find a solution.

+4
source share
3 answers

You can use the DatabaseMetadata interface.

DatabaseMetaData meta = connection.getMetaData();

Example:

DatabaseMetaData meta=conn.getMetaData();
rs= meta.getTables(null, null, tablename, new String[]{"TABLE"});
rs=meta.getPrimaryKeys(null, null, tablename);
while(rs.next())
+2
source

If you have only one restriction in the table, I think this could help:

SELECT OBJECT_NAME(object_id) AS ConstraintName
FROM sys.objects
WHERE OBJECT_NAME(parent_object_id)='application' AND type = 'PK'

If not, just try a different way to access this table.

, SYS.OBJECTS. :)

+2

There is also a system stored procedure that can help you:

EXEC sp_pkeys 'application'

This will return a result set with columns:

  • TABLE_QUALIFIER
  • TABLE_OWNER
  • TABLE_NAME
  • COLUMN_NAME
  • KEY_SEQ
  • PK_NAME

where PK_NAME should be the name of your PK-Constraint

0
source

All Articles