通过SP查看指定表格的DDL信息
以下SP可根据SQL表格名称来查询表中所有字段的名称,类型,精度,小数位数,是否允许为Null值,是否主键,是否计算列,参与的Index名称, 索引中排序类型等. 还可以查看字段的说明,
已通过本人测试验证. 2013-03-10
1 -- Exec spRD_GetTableDDL 'tbasCustomer' 2 3 Create Proc spRD_GetTableDDL 4 @ASqlTableName VarChar(500) 5 as 6 begin 7 SELECT 8 TableName=CASE WHEN C.column_id=1 THEN O.name ELSE N'' END, 9 TableDesc=ISNULL(CASE WHEN C.column_id=1 THEN PTB.[value] END,N''), 10 Column_id=C.column_id, 11 ColumnName=C.name, 12 PrimaryKey=ISNULL(IDX.PrimaryKey,N''), 13 [IDENTITY]=CASE WHEN C.is_identity=1 THEN N'√'ELSE N'' END, 14 Computed=CASE WHEN C.is_computed=1 THEN N'√'ELSE N'' END, 15 Type=T.name, 16 Length=C.max_length, 17 Precision=C.precision, 18 Scale=C.scale, 19 NullAble=CASE WHEN C.is_nullable=1 THEN N'√'ELSE N'' END, 20 [Default]=ISNULL(D.definition,N''), 21 ColumnDesc=ISNULL(PFD.[value],N''), 22 IndexName=ISNULL(IDX.IndexName,N''), 23 IndexSort=ISNULL(IDX.Sort,N''), 24 Create_Date=O.Create_Date, 25 Modify_Date=O.Modify_date 26 FROM sys.columns C 27 INNER JOIN sys.objects O 28 ON C.[object_id]=O.[object_id] AND O.type='U' AND O.is_ms_shipped=0 29 INNER JOIN sys.types T 30 ON C.user_type_id=T.user_type_id 31 LEFT JOIN sys.default_constraints D 32 ON C.[object_id]=D.parent_object_id AND C.column_id=D.parent_column_id AND C.default_object_id=D.[object_id] 33 LEFT JOIN sys.extended_properties PFD 34 ON PFD.class=1 AND C.[object_id]=PFD.major_id AND C.column_id=PFD.minor_id 35 -- AND PFD.name='Caption' -- 字段说明对应的描述名称(一个字段可以添加多个不同name的描述) 36 LEFT JOIN sys.extended_properties PTB 37 ON PTB.class=1 AND PTB.minor_id=0 AND C.[object_id]=PTB.major_id 38 -- AND PFD.name='Caption' -- 表说明对应的描述名称(一个表可以添加多个不同name的描述) 39 LEFT JOIN -- 索引及主键信息 40 ( 41 SELECT 42 IDXC.[object_id], 43 IDXC.column_id, 44 Sort=CASE INDEXKEY_PROPERTY(IDXC.[object_id],IDXC.index_id,IDXC.index_column_id,'IsDescending') 45 WHEN 1 THEN 'DESC' WHEN 0 THEN 'ASC' ELSE '' END, 46 PrimaryKey=CASE WHEN IDX.is_primary_key=1 THEN N'√'ELSE N'' END, 47 IndexName=IDX.Name 48 FROM sys.indexes IDX 49 INNER JOIN sys.index_columns IDXC 50 ON IDX.[object_id]=IDXC.[object_id] AND IDX.index_id=IDXC.index_id 51 LEFT JOIN sys.key_constraints KC 52 ON IDX.[object_id]=KC.[parent_object_id] AND IDX.index_id=KC.unique_index_id 53 INNER JOIN -- 对于一个列包含多个索引的情况,只显示第1个索引信息 54 ( 55 SELECT [object_id], Column_id, index_id=MIN(index_id) 56 FROM sys.index_columns 57 GROUP BY [object_id], Column_id 58 ) IDXCUQ 59 ON IDXC.[object_id]=IDXCUQ.[object_id] AND IDXC.Column_id=IDXCUQ.Column_id AND IDXC.index_id=IDXCUQ.index_id 60 ) IDX 61 ON C.[object_id]=IDX.[object_id] AND C.column_id=IDX.column_id 62 WHERE O.name=@ASqlTableName -- 如果只查询指定表,加上此条件 63 ORDER BY O.name,C.column_id 64 end ; 65