Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Query to generate PKs #2

Open
guilhermebma opened this issue Jun 3, 2018 · 3 comments
Open

Query to generate PKs #2

guilhermebma opened this issue Jun 3, 2018 · 3 comments

Comments

@guilhermebma
Copy link

guilhermebma commented Jun 3, 2018

Hi,

I made a query to generate Pks of tables. The code is below:

SELECT DISTINCT 
         KCU.TABLE_SCHEMA
        ,KCU.TABLE_CATALOG
        ,KCU.TABLE_NAME
        ,'ALTER TABLE '+KCU.TABLE_SCHEMA + '.' + KCU.TABLE_NAME 
                +' CONSTRAINT '+  KCU.CONSTRAINT_NAME 
                +' PRIMARY KEY ("'+lower(KCU.COLUMN_NAME)+'");' as GENERATE_PK
FROM  INFORMATION_SCHEMA.TABLES T
    INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE as KCU ON
            T.TABLE_SCHEMA      = KCU.TABLE_SCHEMA
        AND T.TABLE_NAME        = KCU.TABLE_NAME
        AND T.TABLE_CATALOG     = KCU.TABLE_CATALOG
        AND OBJECTPROPERTY(OBJECT_ID(KCU.CONSTRAINT_SCHEMA + '.' + QUOTENAME(KCU.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
WHERE    T.TABLE_CATALOG        = '%information_schema.database_name%'
     AND T.TABLE_TYPE           = 'BASE TABLE'
     AND T.TABLE_NAME NOT IN ('dtproperties')
ORDER BY 1,2,3;

I hope this code help you to increase your solution.

Tks.

`

@isapir
Copy link
Owner

isapir commented Jul 20, 2018

I am not using it yet to create the PK, but I added it to the Information Schema query following your suggestion at 33b0290

Thank you.

@isapir
Copy link
Owner

isapir commented Jul 25, 2018

I actually had to comment that addition out because the Group By didn't work properly and the query returned duplicate rows

@cinava
Copy link

cinava commented Nov 19, 2019

It's a great tool, however in my case all tables were generated without primary keys.
I'm using SQL Server 2012 and PostgreSQL 12.
Is there any way to correctly generated primary keys and foreign keys?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants