import java.io.FileInputStream; import java.sql.*; import java.util.Properties; public class PkSurvey { public static void main(String[] args) throws Exception { Properties props = new Properties(); try (FileInputStream in = new FileInputStream(args[0])) { props.load(in); } try (Connection conn = DriverManager.getConnection(props.getProperty("url"), props.getProperty("username"), props.getProperty("password"))) { System.out.println("== PK + identity status per table =="); String sql = "SELECT t.name AS tbl, c.name AS col, c.is_identity, " + "(SELECT COUNT(*) FROM sys.key_constraints kc WHERE kc.parent_object_id = t.object_id AND kc.type = 'PK') AS pk_count " + "FROM sys.tables t " + "LEFT JOIN sys.columns c ON c.object_id = t.object_id AND c.name = 'b_id' " + "WHERE t.is_ms_shipped = 0 ORDER BY t.name"; try (Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(sql)) { while (rs.next()) { System.out.printf(" %-22s b_id=%-8s identity=%-5s pk_count=%s%n", rs.getString("tbl"), rs.getString("col"), rs.getBoolean("is_identity"), rs.getInt("pk_count")); } } System.out.println("\n== PK columns for log tables =="); try (Statement st = conn.createStatement(); ResultSet rs = st.executeQuery( "SELECT kc.name AS pk, OBJECT_NAME(kc.parent_object_id) AS tbl, c.name AS col " + "FROM sys.key_constraints kc " + "JOIN sys.index_columns ic ON ic.object_id = kc.parent_object_id AND ic.index_id = kc.unique_index_id " + "JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id " + "WHERE kc.type = 'PK' AND OBJECT_NAME(kc.parent_object_id) IN ('s_log_login','s_log_technical') " + "ORDER BY tbl, ic.key_ordinal")) { while (rs.next()) System.out.printf(" %s.%s (%s)%n", rs.getString("tbl"), rs.getString("col"), rs.getString("pk")); } } } }