Cách tìm khóa ngoại của 1 bảng trong SQL

Hôm nay Admin chia sẽ cách tìm khóa ngoại của 1 bảng trong SQL. Một số cách sau:

1/ Tìm quay lệnh TSQL

Ví dụ bảng roles

      FROM sys.foreign_keys
      WHERE referenced_object_id = object_id('roles');

Hoăc chạy thủ tục

EXEC sp_help 'dbo.roles'

2/ Có thể dùng script bên dưới

SELECT OBJECT_NAME(f.object_id) as ForeignKeyConstraintName,
    OBJECT_NAME(f.parent_object_id) TableName,
    COL_NAME(fk.parent_object_id,fk.parent_column_id) ColumnName,
    OBJECT_NAME(fk.referenced_object_id) as ReferencedTableName,
    COL_NAME(fk.referenced_object_id,fk.referenced_column_id) as ReferencedColumnName

FROM sys.foreign_keys AS f
    INNER JOIN sys.foreign_key_columns AS fk 
        ON f.OBJECT_ID = fk.constraint_object_id
    INNER JOIN sys.tables t
        ON fk.referenced_object_id = t.object_id

WHERE OBJECT_NAME(fk.referenced_object_id) = 'your table name'
    and COL_NAME(fk.referenced_object_id,fk.referenced_column_id) = 'your key column name'

Chúc các bạn thành công

Phương Nguyễn

  1. Junior nói

    What’s up it’s me, I am also visiting this site
    daily, this site is really good and the visitors are
    genuinely sharing good thoughts.

  2. Cesar nói

    Thank you, I’ve recently been searching for info
    approximately this topic for a long time and
    yours is the best I’ve came upon till now. However, what concerning the conclusion? Are
    you positive in regards to the supply?

  3. Monika nói

    Does your site have a contact page? I’m having trouble locating it but, I’d like to shoot you an e-mail.
    I’ve got some creative ideas for your blog you might
    be interested in hearing. Either way, great site and I look forward to seeing
    it develop over time.

  4. Jennifer nói

    Thanks for finally talking about > Cách tìm khóa ngoại của 1 bảng trong SQL –
    IT Sharing – Phuong Nguyen Blog Phương Nguyễn < Loved it!

Được đóng lại, nhưng trackback và pingback được mở.