Finding string value within a database

I had a need to track down which columns in the system had a particular string value. I used the below stored procedure to identify the tables and columns that contained a particular string value.

This script is designed to only find string values within the system, only looking at string fields that are large enough store the entire string.

CREATE PROC [MAGINUS].[SearchAllTables_String]
(
@SearchStr nvarchar(100)
)
AS
BEGIN

CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110), @SearchStr3 nvarchar(110)
SET @TableName = ”
SET @SearchStr2 = QUOTENAME(‘%’ + @SearchStr + ‘%’,char(39))

WHILE @TableName IS NOT NULL

BEGIN
SET @ColumnName = ”
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + ‘.’ + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = ‘BASE TABLE’
AND QUOTENAME(TABLE_SCHEMA) + ‘.’ + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID( QUOTENAME(TABLE_SCHEMA) + ‘.’ + QUOTENAME(TABLE_NAME)
), ‘IsMSShipped’ ) = 0
)

WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN (‘char’, ‘varchar’, ‘nchar’, ‘nvarchar’)
AND CHARACTER_MAXIMUM_LENGTH >= Len(@SearchStr)
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)

IF @ColumnName IS NOT NULL
BEGIN

SET @SearchStr3 = QUOTENAME(@TableName + ‘.’ + @ColumnName, char(39))

–print @TableName + ‘ ‘ + @ColumnName;
–print ‘SELECT ‘ + @SearchStr3 + ‘,’ + @TableName + ‘.’ + @ColumnName + ‘ FROM ‘ + @TableName + ‘ (NOLOCK) WHERE ‘ + @ColumnName + ‘ LIKE ‘ + @SearchStr2

INSERT INTO #Results
EXEC
(
‘SELECT ‘ + @SearchStr3 + ‘,’ + @TableName + ‘.’ + @ColumnName + ‘ FROM ‘ + @TableName + ‘ (NOLOCK) WHERE ‘ + @ColumnName + ‘ LIKE ‘ + @SearchStr2
)
END
END
END

SELECT ColumnName, ColumnValue FROM #Results

END
GO

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s