I am using SQL Server. I have lots of tables and I need to find a particular value and return in which table the value exists.I know in which column the value resides .
My approach: first I get all the tables which can have that column name using cursor. Second I iterate over the cursor one by one, executing a select query on each table with Where
clause to find the value. If the value is in that table , I should print "found in table " .
I need to put a query inside the loop which should print out the table name in which the value exists. I am getting the table name from the cursor, I already have the column name and the value but not able to write dynamic SQL query. Please help me in writing the dynamic query
DECLARE column_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 LIKE '%Agreement_Number%'
ORDER BY TableName;
DECLARE @table_name NVARCHAR(80), @column_value NVARCHAR(30) ;
//@table_name --> table from the cursor
//@column_value --> the value that I am searching for
OPEN column_cursor
FETCH NEXT FROM column_cursor INTO @table_name
WHILE @@FETCH_STATUS = 0
BEGIN
//Not able to put the logic here .
//I should be able to iterate over each table and check for the column_value and print if its exists in the table or not
FETCH NEXT FROM column_cursor INTO @column_name, @table_name
END