做一个数据库比对小工具,把SQL做一个笔记
SELECT object_id AS ID --表ID
,'表' sType
,Name --表名
FROM sys.tables
ORDER BY Name
--字段
SELECT A.Name --字段名
,'字段' sType
,B.name AS typeName --字段类型
,A.max_length AS typeLength --长度(nvarchar要除以2 -1等于max)
,C.text AS defaultValue --默认值
,A.object_id AS PID --表名
,A.is_nullable AS [isNull] --是否为空
,A.is_identity AS isIdentity --是否值增长
, CASE WHEN IC.object_id IS NULL THEN 0 ELSE 1 END AS isPK --是否主键(自带聚集索引)
, CASE WHEN IC.object_id IS NULL THEN 0 ELSE 1 END AS isUnique --是否唯一
FROM sys.columns A
INNER JOIN sys.types B ON A.user_type_id=B.user_type_id
INNER JOIN sys.tables D ON D.object_id=A.object_id
LEFT JOIN sys.syscomments C ON A.default_object_id=C.id
LEFT JOIN sys.objects OB ON OB.parent_object_id=A.object_id AND OB.type='PK'
LEFT JOIN sys.indexes S ON S.name=OB.name
LEFT JOIN sys.index_columns IC ON IC.object_id = A.object_id AND ic.index_id=s.index_id AND ic.column_id=A.column_id
ORDER BY A.object_id,A.column_id
--非主键关联的索引
SELECT A.Name --索引名
,'索引' sType
,D.NAME AS colName --关联字段名
,A.object_id AS PID --表名
,A.type_desc AS typeDesc--索引类型
,A.is_unique AS isUnique --是否唯一
FROM SYS.INDEXES A
JOIN SYS.INDEX_COLUMNS B ON (A.object_id = B.object_id AND A.index_id = B.index_id)
JOIN SYS.TABLES C ON (A.object_id = C.object_id)
JOIN SYS.COLUMNS D ON (A.object_id = D.object_id AND B.column_id = D.column_id)
WHERE A.is_primary_key=0
ORDER BY A.object_id,B.index_column_id
--触发器
SELECT A.parent_id AS PID --表ID
,'触发器' sType
,A.Name --触发器名称
,B.Text --触发器内容
FROM sys.triggers A
INNER JOIN sys.syscomments B ON A.object_id=B.id
ORDER BY A.name
--视图
SELECT A.object_id AS ID
,'视图' sType
,A.Name --视图名
,B.definition Text --存储过程内容
FROM sys.views A
INNER JOIN sys.sql_modules B ON A.object_id=B.object_id
ORDER BY A.name
--存储过程
SELECT A.object_id AS ID
,'存储过程' sType
,A.Name --存储过程名称
,B.definition Text --存储过程内容
FROM sys.procedures A
INNER JOIN sys.sql_modules B ON A.object_id=B.object_id
ORDER BY A.name