I am running the following code to extract all relevant rows from all tables that have a particular column. The outer IF
is supposed to check if the column exists o
Use @whereand to simplify:
exec sp_MSforeachtable
@command1='select * from ? where GCRecord is not null',
@whereand='and exists(select 1 from sys.columns c where c.object_id = o.id
and c.name = ''GCRecord'')'
Please try this dynamic sql. remove comment from exec
when you are ready to run
declare @t varchar(max) = ''
SELECT @t = @t + 'SELECT * FROM ' + a.name + ' WHERE GCRecord IS NOT NULL;' + char(13)
FROM sys.columns b join sys.objects a on
b.Object_ID = a.Object_ID
WHERE b.Name ='CreateDt'
Print @t
--exec (@t)
Use Dynamic query inside begin to avoid inner pre-compilation of code, for tables do not contain column 'GCRecord
'
USE WS_Live
GO
EXECUTE sp_MSforeachtable
'
IF EXISTS( SELECT *
FROM sys.columns
WHERE columns.Object_ID = Object_ID(''?'')
AND Name = ''GCRecord''
)
BEGIN
EXEC(''
IF EXISTS (SELECT * FROM ? WHERE GCRecord IS NOT NULL)
BEGIN
SELECT * FROM ? WHERE GCRecord IS NOT NULL
END
'')
END
'
You are very close. Use "EXEC"
USE WS_Live
EXECUTE sp_MSforeachtable
'
USE WS_Live
IF EXISTS( SELECT *
FROM sys.columns
WHERE columns.Object_ID = Object_ID(''?'')
AND Name = ''GCRecord''
)
BEGIN
EXEC(''SELECT * FROM ? WHERE GCRecord IS NOT NULL'')
END
'