问题描述
我正在尝试设置一个 Sybase 查询,它将给我以下输出:
I'm trying to set up a Sybase query that will give me the following output:
Table KeyType KeyNumber Column
table1 PK 1 table1_id
table1 FK 2 table2_id
table1 FK 3 table3_id
table1 FK 4 table4_id
table1 Unique 5 table1_abc
table1 Unique 5 table1_def
换句话说,我需要每个表的 PK,它拥有的每个外键,以及每个唯一键(不是一个键具有多个元素的情况,例如上面的唯一键,这是由具有相同的 KeyNumber).
In other words, I need the PK for each table, and every foreign key it has, as well as every unique key (not where a key has more than one element, such as the unique key above, this is identified by having the same KeyNumber).
我猜我需要使用 sysobject、syscolumns、syskeys 和 sysconstraints,但我似乎无法弄清楚它们是如何相互关联的.
I'm guessing I need to use sysobject, syscolumns, syskeys and sysconstraints but I can't seem to figure out how they interlink.
谢谢
卡尔
推荐答案
这是一个开始:
SELECT
t.name,
CASE k.type
WHEN 1 THEN 'PK'
WHEN 2 THEN 'FK'
WHEN 3 THEN 'Common'
END,
c.name
FROM
sysobjects t INNER JOIN
syscolumns c ON c.id = t.id INNER JOIN
syskeys k ON k.id = t.id AND c.colid IN (k.key1, k.key2, k.key3, k.key4, k.key5, k.key6, k.key7, k.key8)
WHERE
t.type = 'U' AND k.type in (1,2)
它不包括键 ID,因为我猜你可以以某种方式散列非空表 ID 和 keyN 列来为键生成唯一 ID.
It does not include the key ID, for that I guess you could somehow hash the non-null table ID and keyN columns to produce a unique ID for the key.
它也不包括唯一索引.为此,您可能希望 UNION
使用以下内容:
It also does not include unique indexes. For that you would want to UNION
with something along the lines of:
SELECT
t.name,
'Unique',
c.name
FROM
sysobjects t INNER JOIN
syscolumns c ON c.id = t.id INNER JOIN
sysindexes i ON i.id = t.id
WHERE t.type = 'U'
查看 sysindexes 的 Sybase 手册页关于如何过滤它.
Check out the Sybase manual page for sysindexes on how to filter it.
这篇关于识别 Sybase 表、字段、键、约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!