loop through all tables and delete records

后端 未结 4 1559
借酒劲吻你
借酒劲吻你 2021-01-23 06:20

I\'m new to MsSql and I\'m not sure if this can be done but I figured I\'d ask before I want on my way with the current process..

I need to create a script that loops th

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-23 07:13

    Here is a Sql Fiddle that proves the below query

    You can get the tables from this query:

    SELECT Name, IsChecked = 0
    INTO #Tables
    FROM sys.Tables
    WHERE EXISTS
    (
      SELECT * FROM sys.columns 
      WHERE object_id = OBJECT_ID(sys.Tables.Name) AND sys.columns.Name = 'blah'
    ) 
    

    Then, you can create a dynamic query and execute it for the tables that you found

    WHILE(SELECT COUNT(*) FROM #Tables WHERE IsChecked = 0) > 0
    BEGIN
        SELECT TOP 1 @TableName = Name FROM #Tables WHERE IsChecked = 0
        SET     @DeleteQuery = 'DELETE FROM ' + @TableName  + ' WHERE CorporationID = ''' + @CorporationId + ''''
        EXECUTE sp_executeSQL @DeleteQuery;
        UPDATE #Tables SET IsChecked = 1 WHERE Name = @TableName 
    END
    

提交回复
热议问题