SQL Iterate Over All Tables

后端 未结 4 1956
生来不讨喜
生来不讨喜 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: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
    '
    

提交回复
热议问题