2
我想在我的c#代碼中獲得Sql Server Table
的關係(或外鍵)。 我該怎麼做? 謝謝獲取表格的關係
我想在我的c#代碼中獲得Sql Server Table
的關係(或外鍵)。 我該怎麼做? 謝謝獲取表格的關係
這將讓所有的外鍵dbo.YourTableName
引用:
SELECT
FK = OBJECT_NAME(pt.constraint_object_id),
Referencing_col = pc.name,
Referenced_col = rc.name
FROM sys.foreign_key_columns AS pt
INNER JOIN sys.columns AS pc
ON pt.parent_object_id = pc.[object_id]
AND pt.parent_column_id = pc.column_id
INNER JOIN sys.columns AS rc
ON pt.referenced_column_id = rc.column_id
AND pt.referenced_object_id = rc.[object_id]
WHERE pt.parent_object_id = OBJECT_ID('dbo.YourTableName');
如果你想獲得所有引用dbo.YourTableName
外鍵,這只是稍有不同:
SELECT
-- add these two columns:
[Schema] = OBJECT_SCHEMA_NAME(pt.parent_object_id),
[Table] = OBJECT_NAME(pt.parent_object_id),
FK = OBJECT_NAME(pt.constraint_object_id),
Referencing_col = pc.name,
Referenced_col = rc.name
FROM sys.foreign_key_columns AS pt
INNER JOIN sys.columns AS pc
ON pt.parent_object_id = pc.[object_id]
AND pt.parent_column_id = pc.column_id
INNER JOIN sys.columns AS rc
ON pt.referenced_column_id = rc.column_id
AND pt.referenced_object_id = rc.[object_id]
WHERE pt.referenced_object_id = OBJECT_ID('dbo.YourTableName');
---------^^^^^^^^^^ change this
你可以把它放在存儲過程中,參數化你傳遞給OBJECT_ID
函數的兩部分名稱,然後從C#代碼中調用存儲過程。
請點擊此鏈接[如何對獲得最表-A-外鍵,是指對] [1] [1]:http://stackoverflow.com/questions/ 458913 /如何到獲得最表-A-外鍵,是指對 – KF2