Where do I find Sql Server metadata for column datatypes?

前端 未结 3 1774
礼貌的吻别
礼貌的吻别 2021-01-11 09:52

I know that I can get access to column properties via:

select * 
from sysobjects

What I can\'t find however is information about where to g

3条回答
  •  情深已故
    2021-01-11 10:22

    To build on the answers above, it's often useful to get the column data type in the same format that you need to declare columns.

    For example, varchar(50), varchar(max), decimal(p, s).

    This allows you to do that:

    SELECT 
      [Name]         = c.[name]
    , [Type]         = 
        CASE 
          WHEN tp.[name] IN ('varchar', 'char') THEN tp.[name] + '(' + IIF(c.max_length = -1, 'max', CAST(c.max_length AS VARCHAR(25))) + ')' 
          WHEN tp.[name] IN ('nvarchar','nchar') THEN tp.[name] + '(' + IIF(c.max_length = -1, 'max', CAST(c.max_length / 2 AS VARCHAR(25)))+ ')'      
          WHEN tp.[name] IN ('decimal', 'numeric') THEN tp.[name] + '(' + CAST(c.[precision] AS VARCHAR(25)) + ', ' + CAST(c.[scale] AS VARCHAR(25)) + ')'
          WHEN tp.[name] IN ('datetime2') THEN tp.[name] + '(' + CAST(c.[scale] AS VARCHAR(25)) + ')'
          ELSE tp.[name]
        END
    , [RawType]      = tp.[name]
    , [MaxLength]    = c.max_length
    , [Precision]    = c.[precision]
    , [Scale]        = c.scale
    FROM sys.tables t 
    JOIN sys.schemas s ON t.schema_id = s.schema_id
    JOIN sys.columns c ON t.object_id = c.object_id
    JOIN sys.types tp ON c.user_type_id = tp.user_type_id
    WHERE s.[name] = 'dbo' AND t.[name] = 'MyTable'
    

提交回复
热议问题