CipherIS
asked on
SQL Select Statement
I have a script that searches a database for all fields of data_type = 'text' and puts them in an internal table.
I want to then search for a value in the list of tables that I have in my internal table.
I'm receiving error: Invalid column name --Returns the name of the table in variable @vTableName
I want to then search for a value in the list of tables that I have in my internal table.
DECLARE @Temp TABLE (
RowID INT NOT NULL PRIMARY KEY IDENTITY(1,1),
TableName VARCHAR(250),
ColumnName VARCHAR(250)
)
CREATE TABLE #Search (
TableName VARCHAR(250),
ColumnName VARCHAR(250),
Result VARCHAR(MAX)
)
INSERT INTO @Temp (TableName, ColumnName)
SELECT OBJECT_NAME(c.OBJECT_ID) TableName, c.name ColumnName
FROM sys.columns AS c
JOIN sys.types AS t ON c.user_type_id=t.user_type_id
WHERE t.name = 'text'
ORDER BY c.OBJECT_ID;
SET @RowsToProcess = @@ROWCOUNT
SELECT @RowsToProcess
SELECT * FROM @temp
WHILE (@CurrentRow < @RowsToProcess)
BEGIN
SET @CurrentRow = @CurrentRow + 1
SELECT RowID, TableName, ColumnName
INTO #Temp1
FROM @Temp
WHERE RowID = @CurrentRow
DECLARE @RowID INT = (SELECT TOP 1 RowID FROM #Temp1 ORDER BY RowID DESC)
DECLARE @TableName VARCHAR(250) = (SELECT TOP 1 TableName FROM #Temp1 ORDER BY RowID DESC)
DECLARE @ColumnName VARCHAR(250) = (SELECT TOP 1 ColumnName FROM #Temp1 ORDER BY RowID DESC)
DECLARE @SQL NVARCHAR(MAX)
SET @SQL = N'INSERT INTO #Search (TableName, ColumnName, Result) ' +
'SELECT ' +
@vTableName + ' AS TableName, ' +
'[' + @vColumnName + '] AS ColumnName, ' +
'[' + @vColumnName + '] AS Result ' +
'FROM ' + @vTableName + ' ' +
'WHERE CONVERT(VARCHAR(MAX), [' + @vColumnName + ']) LIKE ' + '''%Search Criteria% '''
PRINT @SQL
EXECUTE(@SQL)
DROP TABLE #Temp1
END
--END WHILE
GO
I'm receiving error: Invalid column name --Returns the name of the table in variable @vTableName
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER