擷取資料庫表的一些資訊

來源:互聯網
上載者:User
擷取資料庫表的一些資訊:

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GetDatabaseSchemaInformation]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GetDatabaseSchemaInformation]
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO

CREATE  Procedure dbo.GetDatabaseSchemaInformation AS
select cols.TABLE_NAME As 'Table Name',
      cols.COLUMN_NAME as 'Column Name',
      cols.DATA_TYPE as 'Data Type',
                  case
                        when cols.DATA_TYPE = 'bigint' then '8 bytes'
                        when cols.DATA_TYPE = 'int' then '4 bytes'
                        when cols.DATA_TYPE = 'smallint' then '2 bytes'
                        when cols.DATA_TYPE = 'tinyint' then '1 byte'
                        when cols.DATA_TYPE = 'bit' then '1 byte'
                        when cols.DATA_TYPE = 'money' then '8 bytes'
                        when cols.DATA_TYPE = 'smallmoney' then '4 bytes'
                        when cols.DATA_TYPE = 'text' then '16 bytes'
                        when cols.DATA_TYPE = 'datetime' then '8 bytes'
                        when cols.DATA_TYPE = 'smalldatetime' then '4 bytes'
                        when cols.DATA_TYPE = 'uniqueidentifier' then '16 bytes'
                        when cols.DATA_TYPE = 'decimal' then convert (varchar,cols.NUMERIC_PRECISION) + ', ' + convert(varchar, cols.NUMERIC_SCALE)
                        else convert(varchar, cols.CHARACTER_MAXIMUM_LENGTH) + ' chars'
                  end as 'Length',
                  case
                        when kcu.CONSTRAINT_NAME is null then 'NO' else 'YES'
                  end as 'PK?',
                  upper(cols.IS_NULLABLE) as 'Allows Nulls',
                  isnull(cols.COLUMN_DEFAULT, '') as 'Default Value'
from INFORMATION_SCHEMA.COLUMNS cols
      join INFORMATION_SCHEMA.TABLES tabs on cols.TABLE_NAME = tabs.TABLE_NAME and
tabs.TABLE_TYPE = 'BASE TABLE'
      left join INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE ctu on cols.TABLE_NAME = ctu.TABLE_NAME and ctu.CONSTRAINT_NAME like 'PK%'
      left join INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu on ctu.CONSTRAINT_NAME = 
kcu.CONSTRAINT_NAME and cols.COLUMN_NAME = kcu.COLUMN_NAME
where tabs.TABLE_NAME <> 'dtproperties'
order by cols.TABLE_NAME, cols.ORDINAL_POSITION

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.