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
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

KathyTheGreat gravatar image

13 1 1 1

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

1 answer: sort newest

Hello kathy,

You can use dynamic sql


       @parameter NVARCHAR(500),

       @outPut VARCHAR(1000)


+'' WHERE Log LIKE ''+''''''%hack%'''''' as ''data()''



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

Cyborg gravatar image

10.6k 36 40 45

+1 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.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

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



Answers and Comments

SQL Server Central

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



asked: Aug 12, 2010 at 05:06 PM

Seen: 1095 times

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