sql: Query to Display Foreign Key Relationships and Name of the Constraint for Each Table in Database

来源:http://www.cnblogs.com/geovindu/archive/2017/05/11/6838999.html
-Advertisement-
Play Games

--20170505 --塗聚文 Geovin Du CREATE DATABASE DuMailSystem GO USE DuMailSystem GO --1查詢表的及備註說明 SELECT Sysobjects.name AS TABLE_NAME, syscolumns.Id, sysco... ...


--20170505
--塗聚文 Geovin Du


CREATE DATABASE DuMailSystem
GO
USE DuMailSystem
GO

--1查詢表的及備註說明
SELECT Sysobjects.name AS TABLE_NAME, syscolumns.Id, syscolumns.name AS COLUMN_NAME,
systypes.name AS DATA_TYPE, syscolumns.length as CHARACTER_MAXIMUM_LENGTH, 
sys.extended_properties.[value] AS COLUMN_DESCRIPTION,  syscomments.text as 
COLUMN_DEFAULT,syscolumns.isnullable as IS_NULLABLE FROM syscolumns 
INNER JOIN systypes 
    ON syscolumns.xtype = systypes.xtype 
    LEFT JOIN sysobjects ON syscolumns.id = sysobjects.id 
  LEFT OUTER JOIN sys.extended_properties ON 
  ( sys.extended_properties.minor_id = syscolumns.colid 
    AND sys.extended_properties.major_id = syscolumns.id) 
  LEFT OUTER JOIN syscomments ON syscolumns.cdefault = syscomments.id 
  WHERE syscolumns.id IN 
    (SELECT id FROM SYSOBJECTS WHERE xtype = 'U') AND (systypes.name <> 'sysname')
   -- ORDER BY syscolumns.colid
   
--2.SQL查詢表的所有欄位的備註說明
SELECT 
(case when a.colorder=1 then d.name else '' end) N'表名', 
a.colorder N'欄位序號', 
a.name N'欄位名', 
(case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '√'else '' 
end) N'標識', 
(case when (SELECT count(*) 
FROM sysobjects 
WHERE (name in 
           (SELECT name 
          FROM sysindexes 
          WHERE (id = a.id) AND (indid in 
                    (SELECT indid 
                   FROM sysindexkeys 
                   WHERE (id = a.id) AND (colid in 
                             (SELECT colid 
                            FROM syscolumns 
                            WHERE (id = a.id) AND (name = a.name))))))) AND 
        (xtype = 'PK'))>0 then '√' else '' end) N'主鍵', 
b.name N'類型', 
a.length N'占用位元組數', 
COLUMNPROPERTY(a.id,a.name,'PRECISION') as N'長度', 
isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) as N'小數位數', 
(case when a.isnullable=1 then '√'else '' end) N'允許空', 
isnull(e.text,'') N'預設值', 
isnull(g.[value],'') AS N'欄位說明' 
FROM syscolumns a 
left join systypes b 
on a.xtype=b.xusertype 
inner join sysobjects d 
on a.id=d.id and d.xtype='U' and d.name<>'dtproperties' 
--AND d.name='MaterialOrderDetails'
left join syscomments e 
on a.cdefault=e.id 
left join sys.extended_properties g 
on a.id=g.major_id AND a.colid = g.minor_id 
order by object_name(a.id),a.colorder   
GO
      
--造成此問題的原因是由於Sql 2005、2008 刪除了系統表 sysproperties 而改用 sys.extended_properties 表所致         
--sql server 2008
SELECT a.[name] as '欄位名稱', (case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '√'else '' end) as '標識'
,b.name '類型'
,a.length '占用位元組數'
,(case when a.isnullable = 1 then '√'else '' end) '允許空'
,isnull(e.text,'') '預設值'
,cast(isnull(g.[value],'') as varchar(100)) AS '欄位說明'
FROM syscolumns  a
left join systypes b
on  a.xtype = b.xusertype
left join sys.syscomments e
on a.cdefault=e.id
 left join sys.extended_properties g
on a.id = g.major_id AND a.colid = g.minor_id
--WHERE a.id =1173579219
--ORDER by a.colorder
GO


SELECT * FROM sys.extended_properties
SELECT * FROM syscolumns
SELECT * FROM sys.syscomments 

SELECT a.name,b.value AS 'Description',b.name,c.name AS 'typename',a.length,d.name as 'TableName' FROM syscolumns AS a,sys.extended_properties AS b,systypes AS c,sysobjects as d
WHERE a.id=b.major_id AND a.colid=b.minor_id
AND a.xtype=c.xusertype
AND  a.id=d.id 



--主鍵
SELECT a.name,b.value AS 'Description',b.name,c.name AS 'typename',a.length,d.name as 'TableName',dbo.F_GetDescriptionTableName(d.id) AS 'TableDescription' FROM syscolumns AS a,sys.extended_properties AS b,systypes AS c,sysobjects as d ,INFORMATION_SCHEMA.KEY_COLUMN_USAGE as e
WHERE a.id=b.major_id AND a.colid=b.minor_id
AND a.xtype=c.xusertype
AND  a.id=d.id 
AND d.xtype='U' and e.TABLE_NAME   = d.name and e.COLUMN_NAME=a.name

--表描述
SELECT * FROM sys.extended_properties  WHERE  minor_id=0
 
SELECT a.id,a.name,b.value AS 'Description' FROM  sysobjects AS a,sys.extended_properties b WHERE a.xtype='U' AND a.id=b.major_id AND minor_id=0




DECLARE @name NVARCHAR(100),@id INT
SET @id=21575115
SELECT @name=CONVERT(NVARCHAR(100),b.value)FROM  sysobjects AS a,sys.extended_properties as b WHERE a.xtype='U' AND a.id=b.major_id AND minor_id=0 AND a.id=@id
SELECT @name AS '表描述'


---表描述
if exists(select 1 from sysobjects where name = 'F_GetDescriptionTableName' and xtype = 'FN') 
drop function F_GetDescriptionTableName 
go 
CREATE function F_GetDescriptionTableName
(
	@id int
) 
returns nvarchar(400) 
as 
begin
declare @str nvarchar(100)
SELECT @str=CONVERT(NVARCHAR(100),b.value)FROM  sysobjects AS a,sys.extended_properties as b WHERE a.xtype='U' AND a.id=b.major_id AND minor_id=0 AND a.id=@id
return isnull(@str,'')
end 
GO



---
SELECT d.name as 'TableName',dbo.F_GetDescriptionTableName(d.id) AS 'TableDescription',a.name as 'FieldName',e.value AS 'FieldDescription',b.name as 'TypeName',a.length as 'Length',a.isnullable as 'IS_NULL' FROM  syscolumns  a,  systypes b,sysobjects d ,INFORMATION_SCHEMA.KEY_COLUMN_USAGE c,sys.extended_properties AS e 
WHERE  a.xtype=b.xusertype  and  a.id=d.id  and  d.xtype='U' and c.TABLE_NAME   = d.name and c.COLUMN_NAME=a.name
AND d.id=e.major_id
AND a.id=e.major_id AND a.colid=e.minor_id
GO

SELECT d.name as 'TableName',a.name as 'FieldName',b.name as 'TypeName',a.length as 'Length',a.isnullable as 'IS_NULL' FROM  syscolumns  a,  systypes b,sysobjects d ,INFORMATION_SCHEMA.KEY_COLUMN_USAGE c WHERE  a.xtype=b.xusertype  and  a.id=d.id  and  d.xtype='U' and c.TABLE_NAME   = d.name and c.COLUMN_NAME=a.name
GO

--Customer,可以加上描述
SELECT c.name   as   FieldName,t.name   as   FieldType,   c.length   as   FieldLength   FROM   SYSCOLUMNS   c   inner   join     systypes   t   on   c.xusertype=t.xusertype   WHERE   c.ID   =   OBJECT_ID('Customer')
GO

SELECT c.name   as   FieldName,t.name as   FieldType,e.value AS FieldDescription ,   c.length   as   FieldLength   FROM   SYSCOLUMNS as  c ,systypes  as t,sys.extended_properties AS e  
WHERE c.xusertype=t.xusertype 
AND c.id=e.major_id AND c.colid=e.minor_id
AND  c.ID   =   OBJECT_ID('Customer')
GO


--查詢表
SELECT * FROM ::fn_listextendedproperty (NULL, 'user', 'dbo', 'table', default, default, default)
 
 --收件箱 Receive,發件箱 
 
IF EXISTS (select * from sysobjects where id = object_id(N'[dbo].SendReceiveMailHost') and OBJECTPROPERTY(id, N'IsUserTable') = 1) 
DROP TABLE SendReceiveMailHost 
GO
 CREATE TABLE SendReceiveMailHost
 (
	SendHostId INT IDENTITY(1,1) PRIMARY KEY,
	SendHostName VARCHAR(100) NOT NULL,
	PopHostName VARCHAR(100) NOT NULL,
	SendUserName VARCHAR(100) NOT NULL,
	SendRealName VARCHAR(100) NOT NULL,
	SendPassword VARCHAR(100) NOT NULL,
	SendPort INT DEFAULT(25) NOT NULL,
	PopPort INT DEFAULT(110) NOT NULL,
	SendEnableSsl BIT DEFAULT(0),
	SendTimeout INT DEFAULT(10000)	
 )
 GO 
 -- 
EXECUTE sp_addextendedproperty N'MS_Description', '收發郵件箱設置表', N'user', N'dbo', N'table', N'SendReceiveMailHost', NULL, NULL
--為欄位添加描述信息
EXECUTE sp_addextendedproperty N'MS_Description', '自動增長ID號', N'user', N'dbo', N'table', N'SendReceiveMailHost', N'column', N'SendHostId'
EXECUTE sp_addextendedproperty N'MS_Description', '發郵件服務地址', N'user', N'dbo', N'table', N'SendReceiveMailHost', N'column', N'SendHostName'
EXECUTE sp_addextendedproperty N'MS_Description', '收件郵件服務地址', N'user', N'dbo', N'table', N'SendReceiveMailHost', N'column', N'PopHostName'
EXECUTE sp_addextendedproperty N'MS_Description', '發郵件箱', N'user', N'dbo', N'table', N'SendReceiveMailHost', N'column', N'SendUserName'
EXECUTE sp_addextendedproperty N'MS_Description', '顯示姓名', N'user', N'dbo', N'table', N'SendReceiveMailHost', N'column', N'SendRealName'
EXECUTE sp_addextendedproperty N'MS_Description', '發件箱密碼', N'user', N'dbo', N'table', N'SendReceiveMailHost', N'column', N'SendPassword'
EXECUTE sp_addextendedproperty N'MS_Description', '發郵件服務埠', N'user', N'dbo', N'table', N'SendReceiveMailHost', N'column', N'SendPort'
EXECUTE sp_addextendedproperty N'MS_Description', '收郵件服務埠', N'user', N'dbo', N'table', N'SendReceiveMailHost', N'column', N'PopPort'
EXECUTE sp_addextendedproperty N'MS_Description', '是否安全SSL', N'user', N'dbo', N'table', N'SendReceiveMailHost', N'column', N'SendEnableSsl'
EXECUTE sp_addextendedproperty N'MS_Description', '發件延長時間秒', N'user', N'dbo', N'table', N'SendReceiveMailHost', N'column', N'SendTimeout' 


SELECT * FROM SendReceiveMailHost;


--收郵件列表ReceiveMail
IF EXISTS (select * from sysobjects where id = object_id(N'[dbo].ReceiveMail') and OBJECTPROPERTY(id, N'IsUserTable') = 1) 
DROP TABLE ReceiveMail 
GO
CREATE TABLE ReceiveMail
(
	ReceiveId   INT IDENTITY(1,1) PRIMARY KEY,
	ReceiveHostId INT NOT NULL
		FOREIGN key references SendReceiveMailHost(SendHostId),
	ContentType VARCHAR(100) NOT NULL,
	ContentEncoding VARCHAR(100) NOT NULL,
	ReceiveTo VARCHAR(100),	
	ReceiveFrom VARCHAR(100),
	ReplyTo VARCHAR(100),	
	ReceiveSubject NVARCHAR(200),
	ReceiveBody NTEXT,
	ReceiveDate DATETIME	
)
GO

EXECUTE sp_addextendedproperty N'MS_Description', '收郵件表', N'user', N'dbo', N'table', N'ReceiveMail', NULL, NULL
--為欄位添加描述信息
EXECUTE sp_addextendedproperty N'MS_Description', '自動增長ID號', N'user', N'dbo', N'table', N'ReceiveMail', N'column', N'ReceiveId'
EXECUTE sp_addextendedproperty N'MS_Description', '收件服務ID,外鍵', N'user', N'dbo', N'table', N'ReceiveMail', N'column', N'ReceiveHostId'
EXECUTE sp_addextendedproperty N'MS_Description', '文件類型', N'user', N'dbo', N'table', N'ReceiveMail', N'column', N'ContentType'
EXECUTE sp_addextendedproperty N'MS_Description', '郵件字元編碼類型', N'user', N'dbo', N'table', N'ReceiveMail', N'column', N'ContentEncoding'
EXECUTE sp_addextendedproperty N'MS_Description', '收件人', N'user', N'dbo', N'table', N'ReceiveMail', N'column', N'ReceiveTo'

EXECUTE sp_addextendedproperty N'MS_Description', '發件人', N'user', N'dbo', N'table', N'ReceiveMail', N'column', N'ReceiveFrom'
EXECUTE sp_addextendedproperty N'MS_Description', '回覆郵件地址', N'user', N'dbo', N'table', N'ReceiveMail', N'column', N'ReplyTo'
EXECUTE sp_addextendedproperty N'MS_Description', '郵件標題', N'user', N'dbo', N'table', N'ReceiveMail', N'column', N'ReceiveSubject'
EXECUTE sp_addextendedproperty N'MS_Description', '郵件內容', N'user', N'dbo', N'table', N'ReceiveMail', N'column', N'ReceiveBody'
EXECUTE sp_addextendedproperty N'MS_Description', '收件日期', N'user', N'dbo', N'table', N'ReceiveMail', N'column', N'ReceiveDate'




---收郵件附件列表 ReceiveAttachments
IF EXISTS (select * from sysobjects where id = object_id(N'[dbo].ReceiveAttachments') and OBJECTPROPERTY(id, N'IsUserTable') = 1) 
DROP TABLE ReceiveAttachments 
GO
CREATE TABLE ReceiveAttachments
(
	 AttachmentId INT IDENTITY(1,1) PRIMARY KEY,
	 AttachmentIdKey  INT NOT NULL
		FOREIGN key references ReceiveMail(ReceiveId),
	 AttachmentFileName NVARCHAR(100) NOT NULL,
	 AttachmentFileUrl NVARCHAR(500) NOT NULL,
	 AttachmentImage IMAGE NOT NULL,
	 AttachmentType VARCHAR(100)	 
)
GO
--來源地址,保存地址
EXECUTE sp_addextendedproperty N'MS_Description', '收郵件附件表', N'user', N'dbo', N'table', N'ReceiveAttachments', NULL, NULL
EXECUTE sp_updateextendedproperty N'MS_Description', '收郵件附件表', N'user', N'dbo', N'table', N'ReceiveAttachments', NULL, NULL
--為欄位添加描述信息
EXECUTE sp_addextendedproperty N'MS_Description', '自動增長ID號', N'user', N'dbo', N'table', N'ReceiveAttachments', N'column', N'AttachmentId'
EXECUTE sp_addextendedproperty N'MS_Description', '外鍵ID', N'user', N'dbo', N'table', N'ReceiveAttachments', N'column', N'AttachmentIdKey'
EXECUTE sp_addextendedproperty N'MS_Description', '文件名稱', N'user', N'dbo', N'table', N'ReceiveAttachments', N'column', N'AttachmentFileName'
EXECUTE sp_addextendedproperty N'MS_Description', '文件地址', N'user', N'dbo', N'table', N'ReceiveAttachments', N'column', N'AttachmentFileUrl'
EXECUTE sp_addextendedproperty N'MS_Description', '文件存儲數據庫', N'user', N'dbo', N'table', N'ReceiveAttachments', N'column', N'AttachmentImage'
EXECUTE sp_addextendedproperty N'MS_Description', '文件類型', N'user', N'dbo', N'table', N'ReceiveAttachments', N'column', N'AttachmentType'


--郵件聯系人(收件人)
IF EXISTS (select * from sysobjects where id = object_id(N'[dbo].Customer') and OBJECTPROPERTY(id, N'IsUserTable') = 1) 
DROP TABLE Customer 
GO
CREATE TABLE Customer
(
	Id INT IDENTITY(1,1) PRIMARY KEY,
	RealName NVARCHAR(100) NOT NULL,
	Email NVARCHAR(100) NOT NULL,
	Sex INT NOT NULL, 
	Title NVARCHAR(50),
	Tel VARCHAR(50)	
)
GO

EXECUTE sp_addextendedproperty N'MS_Description', '郵件聯系人表', N'user', N'dbo', N'table', N'Customer', NULL, NULL
--為欄位添加描述信息
EXECUTE sp_addextendedproperty N'MS_Description', '自動增長ID號', N'user', N'dbo', N'table', N'Customer', N'column', N'Id'
EXECUTE sp_addextendedproperty N'MS_Description', '真實姓名', N'user', N'dbo', N'table', N'Customer', N'column', N'RealName'
EXECUTE sp_addextendedproperty N'MS_Description', '郵件地址', N'user', N'dbo', N'table', N'Customer', N'column', N'Email'
EXECUTE sp_addextendedproperty N'MS_Description', '性別', N'user', N'dbo', N'table', N'Customer', N'column', N'Sex'
EXECUTE sp_addextendedproperty N'MS_Description', '稱呼', N'user', N'dbo', N'table', N'Customer', N'column', N'Title'
EXECUTE sp_addextendedproperty N'MS_Description', '電話', N'user', N'dbo', N'table', N'Customer', N'column', N'Tel'




--發郵件列表 SendMail
IF EXISTS (select * from sysobjects where id = object_id(N'[dbo].SendMail') and OBJECTPROPERTY(id, N'IsUserTable') = 1) 
DROP TABLE SendMail 
GO
CREATE TABLE SendMail
(
	SendId INT IDENTITY(1,1) PRIMARY KEY,
	SendHostId INT NOT NULL 
			FOREIGN key references SendReceiveMailHost(SendHostId),				--
	SendToId INT NOT NULL
	       FOREIGN key references Customer(Id),
	SendSubject NVARCHAR(500) NOT NULL,
	SendBody NTEXT NULL,
	SendIs BIT DEFAULT(1),              --1,ok.0,no.
	SendDate DATETIME DEFAULT(GETDATE())	
)
GO

EXECUTE sp_addextendedproperty N'MS_Description', '發件郵列表', N'user', N'dbo', N'table', N'SendMail', NULL, NULL
--為欄位添加描述信息
EXECUTE sp_addextendedproperty N'MS_Description', '自動增長ID號', N'user', N'dbo', N'table', N'SendMail', N'column', N'SendId'
EXECUTE sp_addextendedproperty N'MS_Description', '發郵件箱ID,外鍵', N'user', N'dbo', N'table', N'SendMail', N'column', N'SendHostId'
EXECUTE sp_addextendedproperty N'MS_Description', '收件人ID,外鍵', N'user', N'dbo', N'table', N'SendMail', N'column', N'SendToId'
EXECUTE sp_addextendedproperty N'MS_Description', '發件標題', N'user', N'dbo', N'table', N'SendMail', N'column', N'SendSubject'
EXECUTE sp_addextendedproperty N'MS_Description', '發件內容', N'user', N'dbo', N'table', N'SendMail', N'column', N'SendBody'
EXECUTE sp_addextendedproperty N'MS_Description', '發件是否成功', N'user', N'dbo', N'table', N'SendMail', N'column', N'SendIs'
EXECUTE sp_addextendedproperty N'MS_Description', '發件時間', N'user', N'dbo', N'table', N'SendMail', N'column', N'SendDate'



--發郵件附件列表 SendAttachments

IF EXISTS (select * from sysobjects where id = object_id(N'[dbo].SendAttachments') and OBJECTPROPERTY(id, N'IsUserTable') = 1) 
DROP TABLE SendAttachments 
GO
CREATE TABLE SendAttachments
(
    AttachmentId INT IDENTITY(1,1) PRIMARY KEY,
	AttachmentIdKey INT
		FOREIGN key references SendMail(SendId),
	AttachmentFileName NVARCHAR(100) NOT NULL,
	AttachmentFileUrl NVARCHAR(500) NOT NULL,
	AttachmentImage IMAGE NOT NULL,
	AttachmentType VARCHAR(100) 
)
GO
--來源地址,保存地址
EXECUTE sp_addextendedproperty N'MS_Description', '發郵件附件表', N'user', N'dbo', N'table', N'SendAttachments', NULL, NULL
--為欄位添加描述信息
EXECUTE sp_addextendedproperty N'MS_Description', '自動增長ID號', N'user', N'dbo', N'table', N'SendAttachments', N'column', N'AttachmentId'
EXECUTE sp_addextendedproperty N'MS_Description', '外鍵ID', N'user', N'dbo', N'table', N'SendAttachments', N'column', N'AttachmentIdKey'
EXECUTE sp_addextendedproperty N'MS_Description', '文件名稱', N'user', N'dbo', N'table', N'SendAttachments', N'column', N'AttachmentFileName'
EXECUTE sp_addextendedproperty N'MS_Description', '文件地址', N'user', N'dbo', N'table', N'SendAttachments', N'column', N'AttachmentFileUrl'
EXECUTE sp_addextendedproperty N'MS_Description', '文件存儲數據庫', N'user', N'dbo', N'table', N'SendAttachments', N'column', N'AttachmentImage'
EXECUTE sp_addextendedproperty N'MS_Description', '文件類型', N'user', N'dbo', N'table', N'SendAttachments', N'column', N'AttachmentType'
GO

--主鍵約束
SELECT
  tab.name AS [表名],
  idx.name AS [主鍵名稱],
  col.name AS [主鍵列名]
FROM
  sys.indexes idx
    JOIN sys.index_columns idxCol 
      ON (idx.object_id = idxCol.object_id 
          AND idx.index_id = idxCol.index_id 
          AND idx.is_primary_key = 1)
    JOIN sys.tables tab
      ON (idx.object_id = tab.object_id)
    JOIN sys.columns col
      ON (idx.object_id = col.object_id
          AND idxCol.column_id = col.column_id);
GO

---唯一約束
SELECT
  tab.name AS [表名],
  idx.name AS [約束名稱],
  col.name AS [約束列名]
FROM
  sys.indexes idx
    JOIN sys.index_columns idxCol 
      ON (idx.object_id = idxCol.object_id 
          AND idx.index_id = idxCol.index_id 
          AND idx.is_unique_constraint = 1)
    JOIN sys.tables tab
      ON (idx.object_id = tab.object_id)
    JOIN sys.columns col
      ON (idx.object_id = col.object_id
          AND idxCol.column_id = col.column_id);
GO

--外鍵約束
select 
  oSub.name  AS  [子表名稱],
  fk.name AS  [外鍵名稱],
  SubCol.name AS [子表列名],
  oMain.name  AS  [主表名稱],
  MainCol.name AS [主表列名]
from 
  sys.foreign_keys fk  
    JOIN sys.all_objects oSub  
        ON (fk.parent_object_id = oSub.object_id)
    JOIN sys.all_objects oMain 
        ON (fk.referenced_object_id = oMain.object_id)
    JOIN sys.foreign_key_columns fkCols 
        ON (fk.object_id = fkCols.constraint_object_id)
    JOIN sys.columns SubCol 
        ON (oSub.object_id = SubCol.object_id  
            AND fkCols.parent_column_id = SubCol.column_id)
    JOIN sys.columns MainCol 
        ON (oMain.object_id = MainCol.object_id  
            AND fkCols.referenced_column_id = MainCol.column_id)
GO

--Check約束
SELECT
  tab.name AS [表名],
  chk.name AS [Check約束名],
  col.name AS [列名],
  chk.definition
FROM
  sys.check_constraints chk
    JOIN sys.tables tab
      ON (chk.parent_object_id = tab.object_id)
    JOIN sys.columns col
      ON (chk.parent_object_id = col.object_id
          AND chk.parent_column_id = col.column_id)
GO


--外鍵約束
SELECT
K_Table = FK.TABLE_NAME,
FK_Column = CU.COLUMN_NAME,
PK_Table = PK.TABLE_NAME,
PK_Column = PT.COLUMN_NAME,
Constraint_Name = C.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
SELECT i1.TABLE_NAME, i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON PT.TABLE_NAME = PK.TABLE_NAME
---- optional:
GO

select 
    t.name as TableWithForeignKey, 
    fk.constraint_column_id as FK_PartNo, c.
    name as ForeignKeyColumn 
from 
    sys.foreign_key_columns as fk
inner join 
    sys.tables as t on fk.parent_object_id = t.object_id
inner join 
    sys.columns as c on fk.parent_object_id = c.object_id and fk.parent_column_id = c.column_id
where 
    fk.referenced_object_id = (select object_id 
                               from sys.tables 
                               where name = 'SendMail')
order by 
    TableWithForeignKey, FK_PartNo
GO


SELECT  obj.name AS FK_NAME,
    sch.name AS [schema_name],
    tab1.name AS [table],
    col1.name AS [column],
    tab2.name AS [referenced_table],
    col2.name AS [referenced_column]
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
GO

SELECT PKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
       PKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O1.SCHEMA_ID)),
       PKTABLE_NAME = CONVERT(SYSNAME,O1.NAME),
       PKCOLUMN_NAME = CONVERT(SYSNAME,C1.NAME),
       FKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
       FKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O2.SCHEMA_ID)),
       FKTABLE_NAME = CONVERT(SYSNAME,O2.NAME),
       FKCOLUMN_NAME = CONVERT(SYSNAME,C2.NAME),
       -- Force the column to be non-nullable (see SQL BU 325751)
       --KEY_SEQ             = isnull(convert(smallint,k.constraint_column_id), sysconv(smallint,0)),
       UPDATE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.OBJECT_ID,'CnstIsUpdateCascade') 
                                        WHEN 1 THEN 0
                                        ELSE 1
                                      END),
       DELETE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.OBJECT_ID,'CnstIsDeleteCascade') 
                                        WHEN 1 THEN 0
                                        ELSE 1
                                      END),
       FK_NAME = CONVERT(SYSNAME,OBJECT_NAME(F.OBJECT_ID)),
       PK_NAME = CONVERT(SYSNAME,I.NAME),
       DEFERRABILITY = CONVERT(SMALLINT,7)   -- SQL_NOT_DEFERRABLE
FROM   SYS.ALL_OBJECTS O1,
       SYS.ALL_OBJECTS O2,
       SYS.ALL_COLUMNS C1,
       SYS.ALL_COLUMNS C2,
       SYS.FOREIGN_KEYS F
       INNER JOIN SYS.FOREIGN_KEY_COLUMNS K
         ON (K.CONSTRAINT_OBJECT_ID = F.OBJECT_ID)
       INNER JOIN SYS.INDEXES I
         ON (F.REFERENCED_OBJECT_ID = I.OBJECT_ID
             AND F.KEY_INDEX_ID = I.INDEX_ID)
WHERE  O1.OBJECT_ID = F.REFERENCED_OBJECT_ID
       AND O2.OBJECT_ID = F.PARENT_OBJECT_ID
       AND C1.OBJECT_ID = F.REFERENCED_OBJECT_ID
       AND C2.OBJECT_ID = F.PARENT_OBJECT_ID
       AND C1.COLUMN_ID = K.REFERENCED_COLUMN_ID
       AND C2.COLUMN_ID = K.PARENT_COLUMN_ID
GO


SELECT
OBJECT_NAME(parent_object_id) 'Parent table',
c.NAME 'Parent column name',
OBJECT_NAME(referenced_object_id) 'Referenced table',
cref.NAME 'Referenced column name'
FROM 
sys.foreign_key_columns fkc 
INNER JOIN 
sys.columns c 
   ON fkc.parent_column_id = c.column_id 
      AND fkc.parent_object_id = c.object_id
INNER JOIN 
sys.columns cref 
   ON fkc.referenced_column_id = cref.column_id 
      AND fkc.referenced_object_id = cref.object_id  where   OBJECT_NAME(parent_object_id) = 'SendMail'
GO

/* CAST IS DONE , SO THAT OUTPUT INTEXT FILE REMAINS WITH SCREEN LIMIT*/
WITH   ALL_KEYS_IN_TABLE (CONSTRAINT_NAME,CONSTRAINT_TYPE,PARENT_TABLE_NAME,PARENT_COL_NAME,PARENT_COL_NAME_DATA_TYPE,REFERENCE_TABLE_NAME,REFERENCE_COL_NAME) 
AS
(
SELECT  CONSTRAINT_NAME= CAST (PKnUKEY.name AS VARCHAR(30)) ,
        CONSTRAINT_TYPE=CAST (PKnUKEY.type_desc AS VARCHAR(30)) ,
        PARENT_TABLE_NAME=CAST (PKnUTable.name AS VARCHAR(30)) ,
        PARENT_COL_NAME=CAST ( PKnUKEYCol.name AS VARCHAR(30)) ,
        PARENT_COL_NAME_DATA_TYPE=  oParentColDtl.DATA_TYPE,        
        REFERENCE_TABLE_NAME='' ,
        REFERENCE_COL_NAME='' 

FROM sys.key_constraints as PKnUKEY
    INNER JOIN sys.tables as PKnUTable
            ON PKnUTable.object_id = PKnUKEY.parent_object_id
    INNER JOIN sys.index_columns as PKnUColIdx
            ON PKnUColIdx.object_id = PKnUTable.object_id
            AND PKnUColIdx.index_id = PKnUKEY.unique_index_id
    INNER JOIN sys.columns as PKnUKEYCol
            ON PKnUKEYCol.object_id = PKnUTable.object_id
            AND PKnUKEYCol.column_id = PKnUColIdx.column_id
     INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
            ON oParentColDtl.TABLE_NAME=PKnUTable.name
            AND oParentColDtl.COLUMN_NAME=PKnUKEYCol.name
UNION ALL
SELECT  CONSTRAINT_NAME= CAST (oConstraint.name AS VARCHAR(30)) ,
        CONSTRAINT_TYPE='FK',
        PARENT_TABLE_NAME=CAST (oParent.name AS VARCHAR(30)) ,
        PARENT_COL_NAME=CAST ( oParentCol.name AS VARCHAR(30)) ,
        PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,     
        REFERENCE_TABLE_NAME=CAST ( oReference.name AS VARCHAR(30)) ,
        REFERENCE_COL_NAME=CAST (oReferenceCol.name AS VARCHAR(30)) 
FROM sys.foreign_key_columns FKC
    INNER JOIN sys.sysobjects oConstraint
            ON FKC.constraint_object_id=oConstraint.id 
    INNER JOIN sys.sysobjects oParent
            ON FKC.parent_object_id=oParent.id
    INNER JOIN sys.all_columns oParentCol
            ON FKC.parent_object_id=oParentCol.object_id /* ID of the object to which this column belongs.*/
            AND FKC.parent_column_id=oParentCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/
    INNER JOIN sys.sysobjects oReference
            ON FKC.referenced_object_id=oReference.id
    INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
            ON oParentColDtl.TABLE_NAME=oParent.name
            AND oParentColDtl.COLUMN_NAME=oParentCol.name
    INNER JOIN sys.all_columns oReferenceCol
            ON FKC.referenced_object_id=oReferenceCol.object_id /* ID of the object to which this column belongs.*/
            AND FKC.referenced_column_id=oReferenceCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/

)

select * from   ALL_KEYS_IN_TABLE
where   
    PARENT_TABLE_NAME  in ('SendMail') 
    or REFERENCE_TABLE_NAME  in ('SendMail')
ORDER BY PARENT_TABLE_NAME,CONSTRAINT_NAME;
GO






SELECT 
   f.name AS 'Name of Foreign Key',
   OBJECT_NAME(f.parent_object_id) AS 'Table name',
   COL_NAME(fc.parent_object_id,fc.parent_column_id) AS 'Fieldname',
   OBJECT_NAME(t.object_id) AS 'References Table name',
   COL_NAME(t.object_id,fc.referenced_column_id) AS 'References fieldname',

   'ALTER TABLE [' + OBJECT_NAME(f.parent_object_id) + ']  DROP CONSTRAINT [' + f.name + ']' AS 'Delete foreign key',

   'ALTER TABLE [' + OBJECT_NAME(f.parent_object_id) + ']  WITH NOCHECK ADD CONSTRAINT [' + 
        f.name + '] FOREIGN KEY([' + COL_NAME(fc.parent_object_id,fc.parent_column_id) + ']) REFERENCES ' + 
        '[' + OBJECT_NAME(t.object_id) + '] ([' +
        COL_NAME(t.object_id,fc.referenced_column_id) + '])' AS 'Create foreign key'
    -- , delete_referential_action_desc AS 'UsesCascadeDelete'
FROM sys.foreign_keys AS f,
     sys.foreign_key_columns AS fc,
     sys.tables t 
WHERE f.OBJECT_ID = fc.constraint_object_id
AND t.OBJECT_ID = fc.referenced_object_id
AND OBJECT_NAME(t.object_id) = 'SendMail'      --  Just show the FKs which reference a particular table
ORDER BY 2
GO

  


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 轉載請註明http://www.cnblogs.com/igoslly/p/6838991.html 【類】的設定與繼承 當設置相同格式的TextView時,已提出在styles.xml自定義格式統一TextView格式,類似【類】即為自定義方法來統一同類型的變數。 1、定義【類】 圖設置了一個名為 ...
  • 1. 單關鍵字匹配 若只需匹配 搜索內容 可以寫的簡單一些,代碼如下: 上面的name是你要顯示整個item內容, mKeyWord 是搜索的關鍵字 holder.tv_name 是當前textview控制項 2.多關鍵字匹配 有的時候我們做搜索的時候 是需要將用戶輸入的關鍵字在服務端做拆分,拆分為多 ...
  • 自定義 用法如下: ...
  • 1.導致Fragment 重疊 和遮蓋的原因 主要還是因為Fragment的狀態保存機制,當系統記憶體不足時,Fragment的主Activity被回收,Fragment的實例並沒有隨之被回收。 Activity被系統回收時,會主動調用onSaveInstance()方法來保存視圖層(View Hie ...
  • 這個適合用於選擇 用戶的一些興趣標簽,個性名片等。 用於將控制項 設置為圓形 的自定義TextView 自定義佈局 用於動態生成多個 控制項 核心類 ...
  • //在向服務端發送請求狀態欄顯示網路活動標誌: [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES]; //請求結束狀態欄隱藏網路活動標誌: dispatch_async(dispatch_get_mai ...
  • 創建一個警告里丟失的文件 托到警報的目錄下 重啟xcode 警告消失 在xcode中選中這個文件右鍵delete再次刪掉文件,就OK了。 ...
  • Fiddler在電腦里已經閑置很久了,之前看是不是伺服器返回問題都是連上AS看輸出的log,但是終歸不如直接抓包來的方便 昨天搞了一下午,手機跟電腦都是連的公司的wifi,手機設置電腦ip和埠的網路代理,結果手機一直是無法上網的狀態。 手機直接訪問ip+埠,也是不行。我懷疑可能是公司路由器的問題 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...