gooderp18绿色标准版
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

83 lines
2.1KB

  1. --Column ID of table A is primary key:
  2. CREATE TABLE A (
  3. ID int4 not null
  4. );
  5. CREATE UNIQUE INDEX AI ON A (ID);
  6. --Columns REFB of table B and REFC of C are foreign keys referenting ID of A:
  7. CREATE TABLE B (
  8. REFB int4
  9. );
  10. CREATE INDEX BI ON B (REFB);
  11. CREATE TABLE C (
  12. REFC int4
  13. );
  14. CREATE INDEX CI ON C (REFC);
  15. --Trigger for table A:
  16. CREATE TRIGGER AT BEFORE DELETE OR UPDATE ON A FOR EACH ROW
  17. EXECUTE PROCEDURE
  18. check_foreign_key (2, 'cascade', 'ID', 'B', 'REFB', 'C', 'REFC');
  19. /*
  20. 2 - means that check must be performed for foreign keys of 2 tables.
  21. cascade - defines that corresponding keys must be deleted.
  22. ID - name of primary key column in triggered table (A). You may
  23. use as many columns as you need.
  24. B - name of (first) table with foreign keys.
  25. REFB - name of foreign key column in this table. You may use as many
  26. columns as you need, but number of key columns in referenced
  27. table (A) must be the same.
  28. C - name of second table with foreign keys.
  29. REFC - name of foreign key column in this table.
  30. */
  31. --Trigger for table B:
  32. CREATE TRIGGER BT BEFORE INSERT OR UPDATE ON B FOR EACH ROW
  33. EXECUTE PROCEDURE
  34. check_primary_key ('REFB', 'A', 'ID');
  35. /*
  36. REFB - name of foreign key column in triggered (B) table. You may use as
  37. many columns as you need, but number of key columns in referenced
  38. table must be the same.
  39. A - referenced table name.
  40. ID - name of primary key column in referenced table.
  41. */
  42. --Trigger for table C:
  43. CREATE TRIGGER CT BEFORE INSERT OR UPDATE ON C FOR EACH ROW
  44. EXECUTE PROCEDURE
  45. check_primary_key ('REFC', 'A', 'ID');
  46. -- Now try
  47. INSERT INTO A VALUES (10);
  48. INSERT INTO A VALUES (20);
  49. INSERT INTO A VALUES (30);
  50. INSERT INTO A VALUES (40);
  51. INSERT INTO A VALUES (50);
  52. INSERT INTO B VALUES (1); -- invalid reference
  53. INSERT INTO B VALUES (10);
  54. INSERT INTO B VALUES (30);
  55. INSERT INTO B VALUES (30);
  56. INSERT INTO C VALUES (11); -- invalid reference
  57. INSERT INTO C VALUES (20);
  58. INSERT INTO C VALUES (20);
  59. INSERT INTO C VALUES (30);
  60. DELETE FROM A WHERE ID = 10;
  61. DELETE FROM A WHERE ID = 20;
  62. DELETE FROM A WHERE ID = 30;
  63. SELECT * FROM A;
  64. SELECT * FROM B;
  65. SELECT * FROM C;
上海开阖软件有限公司 沪ICP备12045867号-1