sql >> Database teknologi >  >> RDS >> Sqlserver

Slet data fra afhængige tabeller

Som der er udenlandske nøglerelationer, kan følgende script få dig i gang med at efterligne en kaskadedelt sletning.

DECLARE @TableName VARCHAR(32)
DECLARE @PrimaryKey VARCHAR(32)

SET @TableName = 'MasterTable'
SET @PrimaryKey = '1'

SELECT  'DELETE FROM '
        + fks.name + '.' + fkt.name
        + ' WHERE '
        + pc.name 
        + ' = '
        + @PrimaryKey
        , fko.name as [FK Name]
        , fk.constraint_column_id as [Col Order]
        , fks.name + '.' + fkt.name as [FK table]
        , pc.name as [FK column]
        , rcs.name + '.' + rct.name as [PK table]
        , rc.name as [PK column]
FROM    sys.foreign_key_columns fk
        -- FK columns
        INNER JOIN sys.columns pc ON fk.parent_object_id = pc.object_id
                                     AND fk.parent_column_id = pc.column_id
        INNER JOIN sys.objects fkt ON pc.object_id = fkt.object_id
        INNER JOIN sys.schemas as fks ON fks.schema_id = fkt.schema_id
        -- referenced PK columns
        INNER JOIN sys.columns rc ON fk.referenced_object_id = rc.object_id
                                     AND fk.referenced_column_id = rc.column_id
        INNER JOIN sys.objects rct ON rc.object_id = rct.object_id
        INNER JOIN sys.schemas as rcs ON rcs.schema_id = rct.schema_id
        -- foreign key constraint name
        INNER JOIN sys.objects fko ON fk.constraint_object_id = fko.object_id
WHERE   rct.Name = @TableName


  1. Socket-undtagelser, når du forsøger at oprette forbindelse til MySql-database fra gitpod IDE (ubuntu-server)

  2. MariaDB UNION Operatør forklaret

  3. SQL-forespørgselsproblem

  4. Sådan omdøbes en primær nøgle i Oracle, så den kan genbruges