Skip to content
Advertisement

Is there a way to also select the row count from the same following query?

Would I be able to add a rowcount to this same query or would I need to create a separate one?

SELECT DISTINCT c.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE, 
                ( 
                    SELECT DISTINCT p.CONSTRAINT_TYPE 
                    FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu 
                        INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS p ON p.CONSTRAINT_NAME=kcu.CONSTRAINT_NAME AND p.CONSTRAINT_TYPE='PRIMARY KEY' 
                    WHERE kcu.TABLE_NAME = c.TABLE_NAME AND kcu.COLUMN_NAME=c.COLUMN_NAME 
                ) AS CONSTRAINT_TYPE, NULL AS DATA_PRECISION, NULL AS DATA_SCALE 
                FROM INFORMATION_SCHEMA.COLUMNS c 

Advertisement

Answer

You can do it with a cte

    with cte as
    (
    SELECT DISTINCT c.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE, 
                    ( 
                        SELECT DISTINCT p.CONSTRAINT_TYPE 
                        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu 
                            INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS p ON p.CONSTRAINT_NAME=kcu.CONSTRAINT_NAME AND p.CONSTRAINT_TYPE='PRIMARY KEY' 
                        WHERE kcu.TABLE_NAME = c.TABLE_NAME AND kcu.COLUMN_NAME=c.COLUMN_NAME 
                    ) AS CONSTRAINT_TYPE, NULL AS DATA_PRECISION, NULL AS DATA_SCALE 
                    FROM INFORMATION_SCHEMA.COLUMNS c 
    )
select *, (select count(*) from cte)  as  _Count
from
cte 
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement