我如何知道 CONSTRAINT_NAME 是主键还是外键?
在 SQL Server 2005 上使用此 SQL,
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = @TableName
AND COLUMN_NAME=@ColumnName
我得到主键和外键。
如何只获取外键? 如何查看约束是主键还是外键?
谢谢
Using this SQL on SQL Server 2005
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_NAME = @TableName
AND COLUMN_NAME=@ColumnName
I get the Primary Keys AND the Foreign Keys.
How can I get only Foreign Keys?
How can I see if a Constraint is a Primary or a Foreign Key?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
找到了一个更优雅的解决方案 此处
为了完整性起见,在下面添加了代码,但所有功劳都归功于 Pinal Dave
如果您只想要主键...
将此添加为附加答案,因为它与我的上一个答案相去甚远:)
Found a much more elegant solution here
Code added below for completeness but all credit goes to Pinal Dave
And if you just want the primary keys...
Added this as an additional answer because it's so far removed from my previous one :)
我在 SQL Server 2005 中使用以下 SQL 来按主键获取约束名称:
按外键获取约束名称:
按约束名称获取外键的表和字段:
按约束名称获取主键的表和字段:
I used the following SQL with SQL Server 2005 to get the Constraint Names by Primary Key:
To get the Constraint Name by Foreing Key:
To get the Foreign Key's Table and Field by Constraint Name:
To get the Primary Key's Table and Field by Constraint Name:
这取决于您的 DBMS,但约束应该在某处具有目标表和列。
如果是外键约束,则目标表将与当前表不同。 尝试
查看
您可以使用的所有神奇列。
It depends on your DBMS but a constraint should have the target table and column somewhere.
If it's a foreign key constraint, the target table will be different to the current table. Try
instead of
to see all the magical columns you can work with.
这不是最优雅的解决方案,但 MS SQL Server 使用 PK & 键的 FK 前缀命名约定,以便您可以使用类似的内容...
如果那是您的 DBMS :)
编辑
当我尝试 Quassnoi 的答案时,我得到了“无效的列名称 'REFERENCED_COLUMN_NAME'”。 错误。
It's not the most elegant of solutions but MS SQL Server uses the PK & FK prefix naming convention for keys so you could use something like...
If that's your DBMS :)
EDIT
When I tried the answer by Quassnoi I got an "Invalid column name 'REFERENCED_COLUMN_NAME'." error.
我用类似的东西。 它也适用于 SQL Server 2000。
这一切都在系统表和视图中,并且有很好的记录。
I use something like that. It works in SQL Server 2000 as well.
It's all in system tables and views which are pretty well documented.