SQL Server: Get table primary key and Foreign Key using sql query

本文涉及的产品
RDS SQL Server Serverless,2-4RCU 50GB 3个月
推荐场景:
云数据库 RDS SQL Server,基础系列 2核4GB
简介: ---所有用户表(主键,外键,描述等信息)涂聚文 20150924 Geovin Du SELECT tbl.[name] AS [TableName], clmns.[name] AS [ColumnName], usrt.[name] AS [DataType], ISNULL(
---所有用户表(主键,外键,描述等信息)涂聚文 20150924 Geovin Du
SELECT  
			  tbl.[name] AS [TableName],
              clmns.[name] AS [ColumnName],
              usrt.[name] AS [DataType],
              ISNULL(baset.[name], N'') AS [SystemType],
              CAST(CASE WHEN baset.[name] IN (N'char', N'varchar', N'binary', N'varbinary', N'nchar', N'nvarchar') THEN clmns.prec ELSE clmns.length END AS int) AS [Length],
              CAST(clmns.xprec AS tinyint) AS [NumericPrecision],
              CAST(clmns.xscale AS int) AS [NumericScale],
              CASE CAST(clmns.isnullable AS bit) WHEN 1 THEN 'YES' ELSE 'NO' END AS [Nulldata],
              defaults.text AS [DefaultValue],
              CAST(COLUMNPROPERTY(clmns.id, clmns.[name], N'IsIdentity') AS int) AS [Identity],
              CAST(COLUMNPROPERTY(clmns.id, clmns.[name], N'IsRowGuidCol') AS int) AS IsRowGuid,
              CAST(COLUMNPROPERTY(clmns.id, clmns.[name], N'IsComputed') AS int) AS IsComputed,
              CAST(COLUMNPROPERTY(clmns.id, clmns.[name], N'IsDeterministic') AS int) AS IsDeterministic,
              CAST(CASE COLUMNPROPERTY(clmns.id, clmns.[name], N'IsIdentity') WHEN 1 THEN IDENT_SEED(QUOTENAME(SCHEMA_NAME(tbl.uid)) + '.' + QUOTENAME(tbl.[name])) ELSE 0 END AS nvarchar(40)) AS [IdentitySeed],
              CAST(CASE COLUMNPROPERTY(clmns.id, clmns.[name], N'IsIdentity') WHEN 1 THEN IDENT_INCR(QUOTENAME(SCHEMA_NAME(tbl.uid)) + '.' + QUOTENAME(tbl.[name])) ELSE 0 END AS nvarchar(40)) AS [IdentityIncrement],
              cdef.[text] AS ComputedDefinition,
              clmns.[collation] AS Collation,
              CAST(clmns.colid AS int) AS ObjectId,
              CAST(ISNULL(pk.is_primary_key, 0)AS bit)AS IsPrimaryKey,
              CAST(ISNULL(IsForeignKey,0) AS bit) AS IsForeignKey,
              ISNULL(pro.Description,'') AS ColumnDescription,
              ISNULL(tpro.TableDescription,'') AS TableDescription              
            FROM
              sys.sysobjects AS tbl
              INNER JOIN sys.syscolumns AS clmns ON clmns.id=tbl.id
              LEFT JOIN sys.systypes AS usrt ON usrt.xusertype = clmns.xusertype
              LEFT JOIN sys.sysusers AS sclmns ON sclmns.uid = usrt.uid
              LEFT JOIN sys.systypes AS baset ON baset.xusertype = clmns.xtype and baset.xusertype = baset.xtype
              LEFT JOIN sys.syscomments AS defaults ON defaults.id = clmns.cdefault
              LEFT JOIN sys.syscomments AS cdef ON cdef.id = clmns.id AND cdef.number = clmns.colid
              LEFT JOIN(SELECT SCHEMA_NAME(o.schema_id)AS TABLE_SCHEMA --是否主键
                      , o.name AS TABLE_NAME
                      , c.name AS COLUMN_NAME
                      , i.is_primary_key
                   FROM sys.indexes AS i JOIN sys.index_columns AS ic ON i.object_id = ic.object_id
                                                                     AND i.index_id = ic.index_id
                                         JOIN sys.objects AS o ON i.object_id = o.object_id
                                         LEFT JOIN sys.columns AS c ON ic.object_id = c.object_id
                                                                   AND c.column_id = ic.column_id
                  WHERE i.is_primary_key = 1)AS pk ON tbl.name = pk.TABLE_NAME
													AND pk.TABLE_SCHEMA='dbo'
                                                  AND pk.COLUMN_NAME=clmns.name
               --是否外键                                   
               LEFT JOIN(SELECT  
    sch.name AS [schema_name],
    tab1.name AS [table],
    col1.name AS [column],
    tab2.name AS [referenced_table],
    col2.name AS [referenced_column],
    CAST(ISNULL(1, 0)AS bit)AS IsForeignKey
FROM sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
    ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
    ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
    ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
    ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id 
INNER JOIN sys.tables tab2
    ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
    ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id) AS  fk ON tbl.name=fk.[table]
    AND fk.schema_name='dbo'
    AND fk.[column]=clmns.name 
 --列备注
    LEFT JOIN (SELECT obj.name AS [TableName], col.name AS [ColumnName],pro.value AS [Description] FROM sys.columns col,sys.extended_properties pro,sys.objects obj
WHERE col.object_id=pro.major_id
AND col.column_id=pro.minor_id
AND obj.object_id=col.object_id) AS pro ON tbl.name=pro.TableName AND clmns.name=pro.ColumnName
--表备注
  LEFT JOIN(SELECT obj.name AS TableName,pros.value AS TableDescription FROM sys.objects obj,sys.extended_properties pros
where obj.object_id=pros.major_id
AND pros.minor_id=0
and obj.type='u') AS tpro ON tbl.name=tpro.TableName

WHERE
           tbl.[type] = 'U'    ---(tbl.[type] = 'U' OR tbl.[type] = 'S')
            --AND SCHEMA_NAME(tbl.uid) = @SchemaName
            --AND tbl.[name] = @TableName
            ORDER BY
              tbl.name
GO


 

相关实践学习
使用SQL语句管理索引
本次实验主要介绍如何在RDS-SQLServer数据库中,使用SQL语句管理索引。
SQL Server on Linux入门教程
SQL Server数据库一直只提供Windows下的版本。2016年微软宣布推出可运行在Linux系统下的SQL Server数据库,该版本目前还是早期预览版本。本课程主要介绍SQLServer On Linux的基本知识。 相关的阿里云产品:云数据库RDS SQL Server版 RDS SQL Server不仅拥有高可用架构和任意时间点的数据恢复功能,强力支撑各种企业应用,同时也包含了微软的License费用,减少额外支出。 了解产品详情: https://www.aliyun.com/product/rds/sqlserver
目录
相关文章
|
3月前
|
SQL 数据库
SQL error : “No query“问题参考
本文介绍了解决SQL中"No query"错误的步骤,包括错误提示、正确的SQL语句写法,以及更多相关参考信息。错误的原因是在构建更新语句时字段赋值之间缺少逗号,导致SQL解析失败。文章还提供了正确格式的SQL语句和相关错误处理的参考链接。
SQL error : “No query“问题参考
|
5月前
|
SQL Oracle 关系型数据库
CREATE TABLE 时的 SQL FOREIGN KEY 约束
【7月更文挑战第24天】CREATE TABLE 时的 SQL FOREIGN KEY 约束。
56 5
|
5月前
|
SQL Oracle 关系型数据库
CREATE TABLE 时的 SQL FOREIGN KEY 约束
【7月更文挑战第19天】CREATE TABLE 时的 SQL FOREIGN KEY 约束
41 8
|
5月前
|
SQL Oracle 关系型数据库
ALTER TABLE 时的 SQL PRIMARY KEY 约束
【7月更文挑战第24天】ALTER TABLE 时的 SQL PRIMARY KEY 约束。
44 3
|
5月前
|
SQL Oracle 关系型数据库
CREATE TABLE 时的 SQL PRIMARY KEY 约束
【7月更文挑战第24天】CREATE TABLE 时的 SQL PRIMARY KEY 约束。
44 2
|
3月前
|
关系型数据库 MySQL 网络安全
5-10Can't connect to MySQL server on 'sh-cynosl-grp-fcs50xoa.sql.tencentcdb.com' (110)")
5-10Can't connect to MySQL server on 'sh-cynosl-grp-fcs50xoa.sql.tencentcdb.com' (110)")
|
5月前
|
SQL 存储 监控
SQL Server的并行实施如何优化?
【7月更文挑战第23天】SQL Server的并行实施如何优化?
126 13
|
5月前
|
SQL
解锁 SQL Server 2022的时间序列数据功能
【7月更文挑战第14天】要解锁SQL Server 2022的时间序列数据功能,可使用`generate_series`函数生成整数序列,例如:`SELECT value FROM generate_series(1, 10)。此外,`date_bucket`函数能按指定间隔(如周)对日期时间值分组,这些工具结合窗口函数和其他时间日期函数,能高效处理和分析时间序列数据。更多信息请参考官方文档和技术资料。
|
5月前
|
SQL 存储 网络安全
关系数据库SQLserver 安装 SQL Server
【7月更文挑战第26天】
66 6
|
5月前
|
存储 SQL C++
对比 SQL Server中的VARCHAR(max) 与VARCHAR(n) 数据类型
【7月更文挑战7天】SQL Server 中的 VARCHAR(max) vs VARCHAR(n): - VARCHAR(n) 存储最多 n 个字符(1-8000),适合短文本。 - VARCHAR(max) 可存储约 21 亿个字符,适合大量文本。 - VARCHAR(n) 在处理小数据时性能更好,空间固定。 - VARCHAR(max) 对于大文本更合适,但可能影响性能。 - 选择取决于数据长度预期和业务需求。
431 1