Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

Search for a Value Throughout Your Database

By Gaurav Goel,

SQL Server is powerful tool to store terabytes of data but what if you need to search for some values thoughout the database? The situation becomes even more complicated when you don't even know the tables' names. So what can be done? Do we need to go to each and every table and then search or is there any smarter way?

The answer to the above question is yes, there is. There are numerous way of doing this but I have done this using cursors. Using a nested loop system you can search the values throughout the database and it will return all the columns with tables containing these values.

Let's take a look at the query:

--Variable Delaration
Declare @keytosearch varchar(max), @Database_Selected varchar(50)

set @keytosearch ='%london%' 
set @Database_Selected= 'Northwind'

Declare @Table varchar(100), @Table_Name Cursor, @Count_Column int, @Result nvarchar(4000),@ID int,@ID_inserted int,@Count_Table int, @data_type varchar(10)

set @ID_inserted=0   
set @Count_Table=0

DECLARE @column varchar(max), @Column_Name CURSOR
--Variable Delaration end

--Second Cursor start
declare @informationName varchar(50), @SysName varchar(50), @Var varchar(5)

set @informationName=@Database_Selected+'.'+'information_schema.COLUMNS'
Set @SysName=@Database_Selected+'.'+'sys.objects'
Set @Var='u'

--Database Selected start
Create Table #SearchResult(ID int identity(1,1) not null, TableName varchar(50), ColumnName varchar(50))
Create Table #SearchTestResult(ID int identity(1,1) not null, ColumnName varchar(max))
Create Table #Table_Name(ID int identity(1,1) not null, table_name varchar(50))

IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='Column_Nam') 
  drop table Column_Nam

insert into #Table_Name exec ('Select name from '+@SysName +' where type= '''+@Var+'''')

--First Cursor open
SET @Table_Name = CURSOR FOR Select table_name from #Table_Name 

open @Table_Name 

Fetch Next from @Table_Name into @Table

WHILE @@FETCH_STATUS = 0
 BEGIN 
  set @Count_Table =@Count_Table+1
  --Second cursor opened
  --print 'Select column_name from  '+@informationName +' where table_name= '''+@Table+''''s
  Exec('SELECT column_name,data_type INTO Column_Nam FROM  '+ @informationName +' where table_name = '''+@Table+'''')
  SET @Column_Name = CURSOR FOR (select column_name from Column_Nam )

  OPEN @Column_Name FETCH NEXT FROM @Column_Name INTO @column
 
  set @Table=@Database_Selected+'.[dbo].['+@Table+']'
  WHILE @@FETCH_STATUS = 0
   BEGIN
    set @data_type= (SELECT top 1 data_type FROM Column_Nam Where column_name= @column)

    if @data_type is not null and (@data_type='varchar' or @data_type='nvarchar' or @data_type='Text')
     begin 
      set @Result=null
      if @column like '%-%' begin  set @Result =('SELECT ''' + @column +''' FROM ' + @Table  
                +' Where ''' + @column + ''' Like '''+@keytosearch+'''') end
        else
		 set @Result =('SELECT ' + @column +' FROM ' + @Table  +' Where ' + @column + ' Like '''+@keytosearch+'''')

      insert into #SearchTestResult exec(@Result)

      set @ID=0
      set @ID=(Select ID from #SearchTestResult where ID=Scope_identity())

	  if @ID is not null 
	   begin
        set @ID_inserted=(select top 1 ID from #SearchResult order by ID desc)
            if @ID_inserted = @ID 
             begin 
              print '' 
             end 
           else  
	        insert into #SearchResult values (@Table,@column)
       end  
    end
    FETCH NEXT FROM @Column_Name INTO @column 
   END  
  CLOSE @Column_Name  
  DEALLOCATE @Column_Name
  --Second cursor closed

  drop table Column_Nam

  Fetch Next from @Table_Name into @Table 
 End 

close @Table_Name  

Deallocate @Table_Name
--First Cursor Closed

Select * from #SearchResult

There are two cursors running in this code one inside another. The outer cursor selects the table name from the database. The inner cursor picks each column and then checks the value passed in for a match. If a record is found then it inserts the table name with the column value into a temp table (#SearchTestResult). At the end it gives all the results.

Searching the keyword "London" in Northwind database gives 

ID  TableName  ColumnName
1  Northwind.[dbo].[Customers] City
2  Northwind.[dbo].[Suppliers] City
3  Northwind.[dbo].[Orders]  ShipCity
4  Northwind.[dbo].[Employees] City

You need to pass the key you want to use to search, the @keytoseach parameter, and the database name  in which you want to search as the @Database_Selected parameter. As the results, you will get tables with columns who contain the search term.

Thanks for reading my post. Hope you enjoyed it :)

Total article views: 6825 | Views in the last 30 days: 9
 
Related Articles
FORUM

Cursor

cursor

FORUM

Updating varchar(max) column

Updating varchar(max) column

FORUM

Varchar column conversion

Converting a column with Data Type of Varchar to Datetime

FORUM

Export VarChar(6500) column

Unable to export VarChar(6500) column to CSV / XLS

FORUM

Cursor

Cursor Examples Wanted

Tags
search    
t-sql    
 
Contribute

Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones
Editor, SQLServerCentral.com

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones