본문 바로가기
Develop/MSSQL

[sql] 모든 제약조건 제거 모든 테이블 제거 쿼리

by 3-stack 2021. 11. 11.
-- 모든 제약조건 제거
SELECT 
  'ALTER TABLE dbo.' + TABLE_CATALOG
  + ' DROP CONSTRAINT' + CONSTRAINT_NAME + ';' AS dropCon
INTO #A
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE 


-- 모든 테이블 제거
SELECT 
  'DROP TABLE dbo.' + TABLE_NAME AS dropTable
INTO #A
FROM INFORMATION_SCHEMA.TABLES  


-- 실행
DECLARE @cnt int = 1
DECLARE @total int;
SELECT @total = COUNT(*) FROM #A
WHILE @cnt <= @total
BEGIN
  DECLARE @SQLString nvarchar(500);
  SELECT @SQLString = query
  FROM (
	SELECT query, ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS rownum
	FROM #A
  ) tb
  WHERE rownum = @cnt

  EXECUTE SP_EXECUTESQL @SQLString

  SET @cnt = @cnt + 1
END

댓글