[SQL SERVER] วิธีแก้ Error: 15138 – The database principal owns a schema in the database, and cannot be dropped

เมื่อวันก่อนได้งานจากหัวหน้าให้เขียน Script เพื่อจัดการ User กับสิทธิื หลังการ Restore ฐานข้อมูล เมื่อลองเขียนคำสั่งเพื่อ Drop User

DROP USER [invest];

พบ Error Message ดังนี้
The database principal owns a schema in the database, and cannot be dropped. (Microsoft SQL Server, Error: 15138)

จาก Error Message ด้านบน สามารถสรุปสาเหตุของปัญหานั้น เกิดจาก User ที่เราต้องการจะ Drop นั้นเป็นเจ้าของ Schema ของฐานข้อมูลนี้ โดยเราสามารถตรวจสอบ Schema ที่ User นั้นๆจัดการอยู่ จากคำสั่ง SQL ดังนี้

SELECT s.name
FROM sys.schemas s
WHERE s.principal_id = USER_ID('invest');

2

หมายเหตุ: sys.schemas มองง่ายเลย คือ กระดาษ Note ที่เก็บข้อมูล Schema ของฐานข้อมูลนั่นเอง

จากข้อมูลข้างต้นได้แสดงให้เห็นว่า User invest เป็นเจ้าของ Schema INVEST อยู่ เราจึงไม่สามารถ Drop User ได้ เราจึงจำเป็นต้องโอนสิทธิ์การดูแล Schema INVEST ไปให้ User อื่น เช่น dbo ตามคำสั่ง ดังนี้

ALTER AUTHORIZATION ON SCHEMA::INVEST TO dbo;

ทดสอบ SELECT Schema ที่ User ดูแลด้วยคำสั่ง ดังนี้

SELECT s.name
FROM sys.schemas s
WHERE s.principal_id = USER_ID('invest');

3

ทดสอบ Drop user อีกครั้งพบว่าสามารถทำได้ ดังรูป

4


Discover more from naiwaen@DebuggingSoft

Subscribe to get the latest posts to your email.