我需要在给定表名,列名和id的数据库中的所有表中返回特定外键的计数。
因此,如果传入的参数是TableName,ColumnName,RecordID,我需要查看将该列作为外键的所有表,并返回匹配的所有RecordID的计数。
我可以看到如何使用游标和动态sql来做到这一点,但我想找出一些更优雅的东西。
我想我真的只需要一个比我聪明的人告诉我你能做或不能做到。
修改
输出应该是这样的:
OtherTable中ID 1的计数为5
OtherTable2中ID 1的计数为10
因此,您可以传入任何表名和记录ID,并让它返回每个引用表的计数
编辑2.我认为应该有一个比这更好的答案,但这就是我想出的。它确实使用动态sql,但至少没有游标。 (它使用冒险工程)
DECLARE @RecID AS INT = 1
DECLARE @TableName AS VARCHAR(255) = 'Product'
CREATE TABLE #temp
(
tablename VARCHAR(255),
ColumnName VARCHAR(255),
sqlStatment VARCHAR(max),
IDCount INT
)
INSERT INTO #temp
(tablename,
ColumnName,
sqlStatment)
SELECT Object_schema_name(f.parent_object_id)
+ '.' + Object_name(f.parent_object_id) AS TableName,
Col_name(fc.parent_object_id, fc.parent_column_id) AS ColumnName,
'update #Temp set IDCount = (select count(*) from '
+ Object_schema_name(f.parent_object_id)
+ '.' + Object_name(f.parent_object_id)
+ ' where '
+ Col_name(fc.parent_object_id, fc.parent_column_id)
+ ' = ' + CONVERT(VARCHAR, @RecID)
+ ') where tablename = '''
+ Object_schema_name(f.parent_object_id)
+ '.' + Object_name(f.parent_object_id) + ''';'
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
WHERE Object_name(f.referenced_object_id) = @TableName
DECLARE @sql AS VARCHAR(max) = ''
SELECT @sql = @Sql + sqlStatment
FROM #temp
EXEC (@sql)
SELECT *
FROM #temp
DROP TABLE #temp
答案 0 :(得分:2)
我认为这就是你想要的:
SELECT COUNT(*)
FROM sys.foreign_key_columns AS fk
JOIN sys.tables AS t ON fk.parent_object_id = t.object_id
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 = 'TableThatContainsTheKey');
答案 1 :(得分:0)
我希望这会有所帮助:
use yourdatabase
select count(*) from sysobjects where xtype='F'
(编辑:抱歉,我的意思是'F'。'PK'代表主键。)