icon picker
Scripts

Lister toutes les relations

SELECT
FK.[name] AS ForeignKeyConstraintName
,SCHEMA_NAME(FT.schema_id) + '.' + FT.[name] AS ForeignTable
,STUFF(ForeignColumns.ForeignColumns, 1, 2, '') AS ForeignColumns
,SCHEMA_NAME(RT.schema_id) + '.' + RT.[name] AS ReferencedTable
,STUFF(ReferencedColumns.ReferencedColumns, 1, 2, '') AS ReferencedColumns
FROM
sys.foreign_keys FK
INNER JOIN sys.tables FT
ON FT.object_id = FK.parent_object_id
INNER JOIN sys.tables RT
ON RT.object_id = FK.referenced_object_id
CROSS APPLY
(
SELECT
', ' + iFC.[name] AS [text()]
FROM
sys.foreign_key_columns iFKC
INNER JOIN sys.columns iFC
ON iFC.object_id = iFKC.parent_object_id
AND iFC.column_id = iFKC.parent_column_id
WHERE
iFKC.constraint_object_id = FK.object_id
ORDER BY
iFC.[name]
FOR XML PATH('')
) ForeignColumns (ForeignColumns)
CROSS APPLY
(
SELECT
', ' + iRC.[name] AS [text()]
FROM
sys.foreign_key_columns iFKC
INNER JOIN sys.columns iRC
ON iRC.object_id = iFKC.referenced_object_id
AND iRC.column_id = iFKC.referenced_column_id
WHERE
iFKC.constraint_object_id = FK.object_id
ORDER BY
iRC.[name]
FOR XML PATH('')
) ReferencedColumns (ReferencedColumns)

Compter les lignes de toutes les tables

-- Définition de la base de données que vous souhaitez analyser
USE PromoComm;
-- Créez une table temporaire pour stocker les résultats
CREATE TABLE #CompteurLignes (TableName NVARCHAR(128), NumberOfRows INT);
-- Utilisez une boucle CURSOR pour parcourir toutes les tables de la base de données
DECLARE @TableName NVARCHAR(128);
DECLARE table_cursor CURSOR FOR
SELECT table_name
FROM information_schema.tables
WHERE table_type = 'BASE TABLE';
-- Variables pour stocker la requête dynamique et le résultat
DECLARE @SqlQuery NVARCHAR(MAX);
DECLARE @NumberOfRows INT;
-- Boucle pour parcourir les tables
OPEN table_cursor;
FETCH NEXT FROM table_cursor INTO @TableName;
WHILE @@FETCH_STATUS = 0
BEGIN
-- Créez la requête dynamique pour compter les lignes dans la table actuelle
SET @SqlQuery = 'INSERT INTO #CompteurLignes (TableName, NumberOfRows) SELECT ''' + @TableName + ''', COUNT(*) FROM [' + @TableName + ']';
-- Exécutez la requête dynamique
EXEC sp_executesql @SqlQuery, N'';
FETCH NEXT FROM table_cursor INTO @TableName;
END
-- Fermez le curseur
CLOSE table_cursor;
DEALLOCATE table_cursor;
-- Sélectionnez les résultats de la table temporaire
SELECT * FROM #CompteurLignes;
-- Supprimez la table temporaire
DROP TABLE #CompteurLignes;

Effacer toutes les lignes de toutes les tables

DECLARE @NAME VARCHAR(100)
DECLARE @SQL NVARCHAR(300)
DECLARE CUR CURSOR FOR
SELECT NAME
FROM SYS.TABLES
WHERE TYPE = 'U'
AND SCHEMA_ID = 1
OPEN CUR
FETCH NEXT FROM CUR INTO @NAME
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = 'DELETE FROM DBO.'+@NAME
PRINT @SQL
EXEC Sp_executesql
@SQL
END
FETCH NEXT FROM CUR INTO @NAME

CLOSE CUR
DEALLOCATE CUR

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.