x

Iterate over system tables to get a list of tables

I need to create a query to first get all the tables with a particular column ( column name is log ) and, once I have this list of tables, iterate over each table to see if the log column contains a specific piece of text. So far I have this:

 SELECT b.name into mytemp
 FROM syscolumns a INNER JOIN sysobjects b ON
 a.id = b.id
 AND
 b.type = 'u'
 WHERE a.name = 'log' 

If I do a select * from mytemp, I get the 5 tables I'm looking for. I need to write some kind of loop to iterate over these 5 tables, do a select log from thistable where log like '%hack%'. I'm close ( at least I'd like to think so ), but I need the rest of this query. I hope someone can help me. Thanks.

more ▼

asked Aug 12, 2010 at 05:06 PM in Default

avatar image

KathyTheGreat
13 1 1 3

(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first

Hello kathy,

You can use dynamic sql

 DECLARE @SQL NVARCHAR(1000),
 
         @parameter NVARCHAR(500),
 
         @outPut VARCHAR(1000)
 
 SET @SQL = 'SELECT @OUT = STUFF((SELECT ''UNION ''+''SELECT ID FROM ''+TABLE_SCHEMA+''.''+TABLE_NAME 
 
 +'' WHERE Log LIKE ''+''''''%hack%'''''' as ''data()''
 
 FROM INFORMATION_SCHEMA.COLUMNS
 
 WHERE COLUMN_NAME = ''Log''
 
 FOR XML PATH('''')),1,5,'''')'
 
 
 SET @parameter = N'@out VARCHAR(1000) OUTPUT'
 
 exec sp_executesql @SQL,@parameter,@out= @OutPut OUTPUT
 
 EXEC (@outPut)

more ▼

answered Aug 12, 2010 at 08:58 PM

avatar image

Cyborg
10.8k 37 55 51

  • use a cursor to iterate and create the dynamic SQL. Also keep in mind that like %somevalue% causes SQL to ignore indexes.

Aug 12, 2010 at 10:43 PM Håkan Winther

Hakan winther, i agree with you, If your filter is like 'SomValue%' then optimizer will not ignore the indexes.

Aug 12, 2010 at 10:56 PM Cyborg

It's giving me an error: Msg 207, Level 16, State 1, Line 1 Invalid column name 'ID'. This is against sql server 2008.

Aug 13, 2010 at 04:53 AM KathyTheGreat

sorry its my fault since i worked with a sample table, replace that id with 'Log'

Aug 13, 2010 at 05:00 AM Cyborg

Cyborg - thank you, thank you. It worked great. I so appreciate your help.

Aug 13, 2010 at 05:03 AM KathyTheGreat
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x7

asked: Aug 12, 2010 at 05:06 PM

Seen: 1231 times

Last Updated: Aug 13, 2010 at 06:12 AM

Copyright 2016 Redgate Software. Privacy Policy