join the MSSQLTips community

Today's Site Sponsor


 

SQL Compare quickly and easily compares and synchronizes SQL Server database schemas
 



Speed up SQL script deployment

Searching and finding a string value in all columns in a SQL Server table

Written By: Greg Robidoux -- 6/18/2008 -- read/post comments -- print -- Bookmark and Share

Rating: (not rated yet) Rate

Problem
Sometimes there is a need to find if a string value exists in any column in your table.  Although there are system stored procedures that do a "for each database" or a "for each table", there is not a system stored procedure that does a "for each column".  So trying to find a value in any column in your database requires you to build the query to look through each column you want to search using an OR operator between each column.  Is there any way this can be dynamically generated?

Solution
Once again this is where T-SQL comes in handy along with the use of system tables or system views.  The code below allows you to search for a value in all text data type columns such as (char, nchar, ntext, nvarchar, text and varchar). 

The stored procedure gets created in the master database so you can use it in any of your databases and it takes three parameters:

  • stringToFind - this is the string you are looking for.  This could be a simple value as 'test' or you can also use the % wildcard such as '%test%', '%test' or 'test%'.
  • schema - this is the schema owner of the object
  • table - this is the table name you want to search, the procedure will search all char, nchar, ntext, nvarchar, text and varchar columns in the table

The first thing you need to do is create this stored procedure by copying the below code and executing it in a query window.

USE master
GO

CREATE PROCEDURE sp_FindStringInTable @stringToFind VARCHAR(100), @schema sysname@table sysname
AS

DECLARE 
@sqlCommand VARCHAR(8000)
DECLARE @where VARCHAR(8000)
DECLARE @columnName sysname
DECLARE @cursor VARCHAR(8000)

BEGIN TRY
   
SET @sqlCommand 'SELECT * FROM ' @schema '.' @table ' WHERE'
   
SET @where ''

   
SET @cursor 'DECLARE col_cursor CURSOR FOR SELECT COLUMN_NAME
   FROM ' 
DB_NAME() + '.INFORMATION_SCHEMA.COLUMNS
   WHERE TABLE_SCHEMA = ''' 
@schema '''
   AND TABLE_NAME = ''' 
@table '''
   AND DATA_TYPE IN (''char'',''nchar'',''ntext'',''nvarchar'',''text'',''varchar'')'

   
EXEC (@cursor)

   
OPEN col_cursor   
   
FETCH NEXT FROM col_cursor INTO @columnName   

   
WHILE @@FETCH_STATUS 0   
   
BEGIN   
       IF 
@where <> ''
           
SET @where @where ' OR'

       
SET @where @where ' ' @columnName ' LIKE ''' @stringToFind ''''
       
FETCH NEXT FROM col_cursor INTO @columnName   
   
END   

   CLOSE 
col_cursor   
   
DEALLOCATE col_cursor 

   
SET @sqlCommand @sqlCommand @where
   
--PRINT @sqlCommand
   
EXEC (@sqlCommand
END TRY
BEGIN CATCH
   
PRINT 'There was an error'
   
IF CURSOR_STATUS('variable''col_cursor') <> -3
   
BEGIN
       CLOSE 
col_cursor   
       
DEALLOCATE col_cursor 
   
END
END 
CATCH

Once the stored procedure has been created you can run some tests.

Here are some tests that were done against the AdventureWorks database.

Find the value 'Irv%' in the Person.Address table.

USE AdventureWorks
GO
EXEC sp_FindStringInTable 'Irv%''Person''Address'

Find the value '%land%' in the Person.Address table.

USE AdventureWorks
GO
EXEC sp_FindStringInTable '%land%''Person''Address'

Find the value '%land%' in the Person.Contact table.

USE AdventureWorks
GO
EXEC sp_FindStringInTable '%land%''Person''Contact'

That's all there is to it.  Once this has been created you can use this against any table and any database on your server.

Next Steps

  • Add this to your scripts toolbox in case you have the need to search through a table to find a certain value.
  • Take a look at this tip that allows you search across all tables in your database.
  • Thanks to Paul (pws) for the idea for this tip
  • One thing to keep in mind is that if you are using the % in front of the value such as '%land' this will force SQL Server to scan the table and not use the indexes.  Also, since you are searching through all columns using an OR clause it is a pretty good bet that you will do a table scan, so be aware of this on large tables.
Readers Who Read This Tip Also Read Free Live Webcast Comment or Ask Questions About This Tip


Wasting time running multiple scripts against multiple SQL Servers manually?

Try SQL Multi Script and execute all those scripts with just one mouse click.

Execute multiple scripts against multiple SQL Servers with a single click

"Just tried SQL Multi Script and very impressed with it. Talk about reducing work load!"

Neil Abrahams SQL Server DBA/Developer

SQL Multi Script Red Gate Software - ingeniously simple tools

Get Our Tips Newsletter

We keep 50,000+ SQL Server professionals informed.



Idera - SQL secure

Idera SQL secure collects and analyzes permissions data from SQL Server and Active Directory as well as the file system and registry to show who has access to what database objects and how that access is granted. SQL secure also monitors changes made to access rights so that unapproved changes can be easily identified and fixed. SQL secure also collects and evaluates key security settings within SQL Server and provides proactive recommendations to improve server security.

Download now!

More SQL Server Tools
SQL comparison toolset

SQL defrag manager

SQL Refactor

SQL compliance manager

SQL secure


Sponsor Information
Free SQL Server performance monitoring dashboard – Idera SQL check

Quickly and accurately deploy database changes with Red Gate's SQL Compare – the industry standard comparison and deployment tool.

SQL Server Consultants - What you don't know could be your biggest asset - Guaranteed Results

Valuable SharePoint resources all for free – Check it out

Free SQL Server web casts for DBAs and Developers on Performance Tuning, Development, Administration, Disaster Recovery, Replication and more....



Copyright (c) 2006-2010 Edgewood Solutions, LLC All rights reserved
privacy statement | disclaimer | copyright | advertise | write for mssqltips | feedback | about
Some names and products listed are the registered trademarks of their respective owners.


CareerQandA.com | MSSharePointTips.com | MSSQLTips.com