Find Out Tables and Coluns Based on Data in SQL Server



DECLARE @Query NVARCHAR(MAX), @Column NVARCHAR(100), @Table NVARCHAR(100)
DECLARE @Search NVARCHAR(100)
SET @Search = 'Full-time'

CREATE TABLE #Results(Table_Name VARCHAR(100), Column_Name VARCHAR(100))

DECLARE Col CURSOR FOR
SELECT Table_Name, Column_Name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLLATION_NAME IS NOT NULL
ORDER BY TABLE_NAME, ORDINAL_POSITION

OPEN Col
FETCH NEXT FROM Col INTO @Table, @Column
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @Query = 'IF EXISTS (SELECT * FROM '+QUOTENAME(@Table)+' WHERE '+QUOTENAME(@Column)+'='''+@Search+''')
                    SELECT '''+@Table+''','''+@Column+''''

    INSERT INTO #Results
    EXEC sp_executesql @Query
    FETCH NEXT FROM Col INTO @Table, @Column
END
CLOSE Col
DEALLOCATE Col

SELECT * FROM #Results

0 comments:

Post a Comment