我在变量中有主键名,我需要找到它们所属的表。 db有很多表,因此不能选择线性搜索。
答案 0 :(得分:1)
您可以使用information_schema
表。如果主键名是表中的第一列,则可以执行以下操作:
select table_name
from information_schema.columns
where column_name in (<your list here>) and
ordinal_position = 1;
否则,你必须通过约束来获得你想要的东西。类似的东西:
select kcu.table_name, kcu.column_name
from information_schema.table_constraints tc join
information_schema.key_column_usage kcu
on tc.contraint_name = kcu.contraint_name and
tc.table_name = kcu.table_name
where tc.contraint_type = 'PRIMARY KEY' and
column_name in (<your list here>);
您也可以使用系统表和视图执行此操作。
答案 1 :(得分:0)
你可以试试这个::
SELECT table_name
FROM information_Schema.columns
WHERE column_name='dept_id'
and ordinal_position = 1;
答案 2 :(得分:0)
这应该有用,请尝试一下:
SELECT table_name
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
AND column_name in (select column_name from <your list here>)
如果将主键约束设置为“CREATE TABLE”查询中第一列以外的任何列,则下面的解决方案将无效。
select table_name
from information_schema.columns
where column_name in (select column_name from <your list here>) and
ordinal_position = 1
例如,如果我们创建这样的表,它将无效:
create table sample1
(
field1 int,
field2 int primary key
)
如果我错了,请纠正我。
答案 3 :(得分:0)
以下查询根据约束名称
提供表名select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS
where CONSTRAINT_NAME ='<ConstraintName>'
答案 4 :(得分:0)
要使用主键名称查找表名,请按照以下查询
class data {
public data: [number, string]; //would be hidden later and accessed by getters for left and right
constructor (left: number, right: string) {
this.data=[left, right];
}
public equals(rhs: data): boolean {
return this.data[0] === rhs.data[0] && this.data[1] === rhs.data[1];
}
}
let theSet = new Set();
let n = 0;
let s = "hello world";
let dat1 = new data(n, s);
theSet.add(dat1);
let dat2 = new data(n, s);
if (theSet.has(dat2)) {
alert("contains");
} else {
alert("doesn't contain");
}
答案 5 :(得分:0)
从以上答案中得到改善
select kcu.table_name, kcu.column_name, *
from information_schema.table_constraints tc join
information_schema.key_column_usage kcu
on tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME and
tc.table_name = kcu.table_name
where tc.CONSTRAINT_NAME = 'PK__DC_INPUT__7EA5540496A9FD5D'
答案 6 :(得分:0)
SELECT [TABLE_NAME]
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_NAME = 'YourPrimaryKey';