Search code examples
sql-serversql-server-2014

Get all tables which has primary key with data type uniqueidentifier in SQL Server


I need to write a query that will return all tables name which has Primary key column with data type uniqueidentifier.

Can anyone please help me.


Solution

  • Using sql server object catalog views:

    select 
         IndexName  = i.name
       , SchemaName = schema_Name(t.schema_id)
       , TableName  = t.Name
       , ColumnName = c.Name 
       , TypeName   = type_name(c.user_type_id)
    from sys.tables t
      inner join sys.indexes as i on
                t.object_id = i.object_id
            and i.is_primary_key = 1
      inner join sys.index_columns as ic on 
            i.object_id = ic.object_id
        and i.index_id = ic.index_id 
      inner join sys.columns as c on 
            c.column_id = ic.column_id
        and c.object_id = ic.object_id 
        and type_name(c.user_type_id) = 'uniqueidentifier'
    

    rextester link: http://rextester.com/SAL18997