SQL如何查找具有条件的多于1行的表?

时间:2018-12-12 14:56:26

标签: sql sql-server

我有一个超过6000个表的数据库。我正在寻找已填充某些条件的表(即person_id = 123)。

这可能吗?

我可以获取具有{_1}}且具有person_id的表的列表,但要查找具有row count > 0person_id = 123的表。

这给出了包含rowcount > 0person_id的表的列表。

rowcount

3 个答案:

答案 0 :(得分:2)

我认为这将为您使用光标做到这一点

declare @t varchar(100)
    ,@sql varchar(max)

create table #finished (tbls varchar(100))

DECLARE db_cursor CURSOR FOR 
select table_name
from INFORMATION_SCHEMA.columns
where column_name = 'person_id'

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @t 

WHILE @@FETCH_STATUS = 0  
BEGIN  
      set @sql ='insert into #finished
             select distinct ''' +@t + ''''+
             ' from ' + @t +
             ' where person_ID=123'

      exec(@sql)

      FETCH NEXT FROM db_cursor INTO @t 
END 

CLOSE db_cursor  
DEALLOCATE db_cursor


select * from #finished
drop table #finsihed

答案 1 :(得分:1)

你在这里。

CREATE TABLE #tmp
(
    TableName       NVARCHAR(255)
    , [RowCount]    INT
)

DECLARE Csr cursor for
SELECT DISTINCT t.[name] AS tablename
FROM sys.columns c 
    INNER JOIN sys.tables t 
        ON c.object_id = t.object_id
WHERE c.[name] = 'PersonID'

DECLARE
    @TABLE_NAME NVARCHAR(255)
    , @SQL  VARCHAR(MAX)

set nocount on
OPEN Csr
FETCH NEXT FROM Csr INTO @TABLE_NAME
WHILE (@@fetch_status <> -1)
 BEGIN
    IF (@@fetch_status <> -2)
     BEGIN
    SET @SQL = 'INSERT INTO #tmp (TableName, [RowCount]) SELECT ''' + @TABLE_NAME + ''', COUNT(*) FROM ' + @TABLE_NAME + ' WHERE PersonID = 123'
    EXECUTE(@SQL)
     END
    FETCH NEXT FROM Csr INTO @TABLE_NAME    
 END
CLOSE Csr
DEALLOCATE Csr

SELECT *
FROM #tmp
WHERE [RowCount] > 0

DROP TABLE #tmp

答案 2 :(得分:0)

使用动态SQL:

<xsl:template match="/analystePurchaseInvoices">
    <xsl:apply-templates select="purchaseInvoice"/> 
</xsl:template>