SQL Iterate Over All Tables

后端 未结 4 1955
生来不讨喜
生来不讨喜 2021-01-24 07:13

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

相关标签:
4条回答
  • 2021-01-24 07:43

    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'')' 
    
    0 讨论(0)
  • 2021-01-24 07:50

    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)
    
    0 讨论(0)
  • 2021-01-24 07:52

    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
    '
    
    0 讨论(0)
  • 2021-01-24 07:52

    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
    '
    
    0 讨论(0)
提交回复
热议问题