【发布时间】:2015-03-08 22:37:44
【问题描述】:
我正在尝试创建一个存储过程,当在该表中提供一个表名和一个 ID 时,它将返回一个外键列 + 其值的列表(一个包含两列的表)。保证一个 ID 是唯一的。结果应包含与外键列数相等的行数。如果没有找到外键,则应生成 NULL 行,例如Key = NULL, Value = NULL.
考虑以下示例表和数据:
员工表:
Id | Name | AddressId | JobId
----|------------|-----------|-------
1 | John Smith | 2 | 3
Foreign keys:
- FK_Employee_Address
- FK_Employee_Job
地址表:
Id | Street | Suite | City | Postal Code | CountryId
----|-----------|--------|----------|-------------|-----------
2 | 1 Main St | 101 | New York | 10001 | 4
Foreign keys:
- FK_Address_Country
国家表:
Id | Name
----|------
4 | USA
职位表:
Id | Title
-----|-----------
3 | Developer
问题:如何在生成的 SQL 查询中获取所有外键列 + 它们的值,每行一个?
测试用例 1:
spGetForeignKeyColumns 'Employee', 1
Key | Value
----------|------
AddressId | 2
JobId | 3
测试用例 2:
spGetForeignKeyColumns 'Address', 2
Key | Value
----------|------
CountryId | 4
测试用例 3:
spGetForeignKeyColumns 'Country', 4
Key | Value
----------|------
NULL | NULL
假设 Id 总是 int 是安全的,所以不会有任何类型冲突。
尝试的解决方案。我知道如何使用以下 SELECT 语句检索给定表的所有外键列没有值:
SELECT * FROM (
SELECT f.name AS ForeignKey, OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id, fc.parent_column_id) AS ColumnName,
OBJECT_NAME(f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id, fc.referenced_column_id) AS ReferenceColumnName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id) fk
WHERE TableName = @TableName
上面的 Employee 表会产生以下结果:
ForeignKey | TableName | ColumnName | ReferenceTableName | ReferenceColumnName
---------------------|-----------------|------------|--------------------|---------------------
FK_Employee_Address | Employee | AddressId | Address | Id
FK_Employee_Job | Employee | JobId | Job | Id
【问题讨论】:
标签: sql sql-server stored-procedures foreign-keys