简体   繁体   English

查找公共列设置为值的所有数据库表

[英]Find all database tables where a common column is set to a value

All database tables have a UserId field of [uniqueidentifier] type. 所有数据库表都具有[uniqueidentifier]类型的UserId字段。

I need to query the entire database and get the list of tables that have UserId set to a specific value. 我需要查询整个数据库,并获取将UserId设置为特定值的表的列表。 Right now I achieved this by using cursor and the results are horrible and are difficult to read. 现在,我通过使用游标实现了这一目标,结果令人震惊且难以阅读。 How can I improve this query to retrieve back a clear list with tables and count of record that have UserId set to a specific value, instead of using this: 我该如何改进此查询以取回具有将UserId设置为特定值的表和记录计数的清除列表,而不使用以下方法:

DECLARE @TableName VARCHAR(127);
DECLARE @Value VARCHAR(512);
DECLARE @SqlCommand varchar(1000)

--Use cursor to loop through database tables that contain UserId column
DECLARE db_cursor CURSOR FOR 
    SELECT t.name AS TableName
    FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
    WHERE c.name = 'UserId';
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @TableName;
WHILE @@FETCH_STATUS = 0  
BEGIN  

 --Check if the next table has any UserId matching the where clause
 EXEC('SELECT COUNT(UserId) ,  ''' + @TableName + ''' FROM ' + @TableName + ' WHERE UserId = ''FF13ACCA-022C-4296-AB3D-A35700E35BB3''');


   FETCH NEXT FROM db_cursor INTO @TableName;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;

You made all the difficult part, just put the value in a temp table and select them once you've finished. 您做了所有困难的部分,只需将值放在临时表中,然后在完成后选择它们。

DECLARE @TableName VARCHAR(127);
DECLARE @Value VARCHAR(512);
DECLARE @SqlCommand varchar(1000)

--Creta temp table
CREATE TABLE #Results (Number int, Tablename sysname)
--Use cursor to loop through database tables that contain UserId column
DECLARE db_cursor CURSOR FOR 
    SELECT t.name AS TableName
    FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
    WHERE c.name = 'UserId';
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @TableName;
WHILE @@FETCH_STATUS = 0  
BEGIN  

 --Check if the next table has any UserId matching the where clause
 EXEC('INSERT INTO #Results (Number, ''' + @TableName + ''') SELECT COUNT(UserId) ,  ''' + @TableName + ''' FROM ' + @TableName + ' WHERE UserId = ''FF13ACCA-022C-4296-AB3D-A35700E35BB3''');

   FETCH NEXT FROM db_cursor INTO @TableName;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;

SELECT * FROM #Results
DROP TABLE #Results

I cannot test it but this should be the way 我无法测试,但这应该是这样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM