在SQL Server中动态确定给定字段名称的表名称
奇怪的情况:我试图从我的代码中删除一些硬编码。有一种情况,我有一个字段,比如说“CityID”,并且使用此信息,我想找出哪个表包含名为 CityID 的主键。
从逻辑上讲,您会说它可能是一个名为“City”的表,但它不是......该表称为“Cities”。数据库命名中还存在一些其他不一致,因此我永远无法确定删除字符串“ID”并找出复数是否就足够了。
注意:一旦我发现 CityID 引用了名为 Cities 的表,我将执行联接以即时将 CityID 替换为城市名称。如果 someonw 也能告诉我如何找到给定名称的表中的第一个 varchar 字段,我将不胜感激。
Strange situation: I am trying to remove some hard coding from my code. There is a situation where I have a field, lets say "CityID", and using this information, I want to find out which table contains a primary key called CityID.
Logically, you'd say that it's probably a table called "City" but it's not... that table is called "Cities". There are some other inconsistencies in database naming hence I can never be sure if removing the string "ID" and finding out the plural will be sufficient.
Note: Once I figure out that CityID refers to a table called Cities, I will perform a join to replace CityID with city name on the fly. I will appreciate if someonw can also tell me how to find out the first varchar field in a table given its name.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
获取指定表的列信息:
To get column information from the specified table:
从 information_schema.columns 中选择 table_name,其中 column_name='CityID'
select table_name from information_schema.columns where column_name='CityID'
您可以使用 INFORMATION_SCHEMA 表来读取有关数据库的元数据。
有关 INFORMAITON_SCHEMA 内容的入门知识,请参阅INFORMATION_SCHEMA,数据库映射
You can use the INFORMATION_SCHEMA tables to read metadata about the database.
For a primer in what's in the INFORMAITON_SCHEMA, see INFORMATION_SCHEMA, a map to your database
您寻求的信息都可以在信息架构视图中找到。请注意,您会发现许多来源告诉您如何直接查询这些是视图的底层系统表 - 我必须承认,当我只是为了快速找到某些内容时我也会这样做 - 但应用程序的推荐方法是通过这些观点。
例如,要查找
CityID
列:要查找表中的第一个
varchar
字段:The information you seek is all available in the information schema views. Note that you will find many sources telling you how to directly query the underlying system tables that these are views onto - and I must admit that I do the same when it's just to find something out quickly - but the recommended way for applications is to go through these views.
For example, to find your
CityID
column:To find the first
varchar
field in a table:据我从您的问题中了解到,您想要查找主键中包含 CITYID 列的表
您可以使用 SQL Server 系统视图,如 sysindexes 和 sysindexkeys,如 SQL 教程中所示 查询数据库表主键包括复合主键所形成的
As I understand from your question, you want to find tables which contain CITYID column in primary key
You can use SQL Server system views like sysindexes and sysindexkeys as shown in SQL tutorial to query database table primary keys including composite primary keys which are formed