The task is to scroll through all tables and columns to find the table and column names containig the searched value. The script I use is:
IF Object_id('tempdb..#temp_sar') IS NOT NULL
DROP TABLE #temp_sar
go
CREATE TABLE #temp_table
(
[table_name] VARCHAR,
[column_name] VARCHAR
)
DECLARE @Table_Name VARCHAR
DECLARE @Column_Name VARCHAR
DECLARE @Search_Value UNIQUEIDENTIFIER = CONVERT(UNIQUEIDENTIFIER, '303D9191-E201-4299-809E-FC7B0213F73C')
DECLARE @CURSOR CURSOR
SET @CURSOR = CURSOR scroll FOR
(SELECT s.table_name,
s.column_name
FROM information_schema.columns s
WHERE s.data_type = 'uniqueidentifier')
OPEN @CURSOR
FETCH next FROM @CURSOR INTO @Table_Name, @Column_Name
WHILE @@FETCH_STATUS = 0
BEGIN
IF @Search_Value = EXEC ('select distinct' + @Column_Name + 'from'
+ @Table_Name + 'where' + @Column_Name + '='
+ @Search_Value)
INSERT INTO #temp_table ([table_name], [column_name])
VALUES (@Table_Name, @Column_Name)
FETCH next FROM @CURSOR INTO @Table_Name, @Column_Name
END
CLOSE @CURSOR
SELECT * FROM #temp_table;
When this is executed, I get an error:
Incorrect syntax near the keyword 'EXEC'
Please help me make this code work