简体   繁体   English

如何使用sql在xml中定义PK?

[英]How to define PK in xml using sql?

Is it possible to create the Primary key and Foreign key tag in xml using sql? 是否可以使用sql在xml中创建主键和外键标签? like 喜欢

  <Column Name="ID" DataType="INTEGER" IsPrimaryKey="true" />
  <ForeignKey SourceTable="Product" TargetTable="Market">
  <ColumnMap Source="ID" Target="ID" Ordinal="1" />
  </ForeignKey>

I use following part but it does not shows the PK and FK part: 我使用以下部分,但未显示PK和FK部分:

    select COLUMN_NAME as '@Name',
           Data_type as '@DataType',
           character_octet_length as '@Length'
           FROM information_schema.COLUMNS 
    FOR XML PATH ('Column'), TYPE

An important thing to bear in mind is that primary and foreign keys are defined at table level, not against individual columns, which can lead to quite complex queries to build up the data you require. 要记住的重要一点是,主键和外键是在表级别定义的,而不是针对单个列定义的,这可能导致相当复杂的查询来构建所需的数据。 It is, for example, quite possible to have a primary key covering multiple fields; 例如,很有可能拥有一个覆盖多个字段的主键。 it's also quite common for a column to be defined as a foreign key on a large number of tables other than the one it belongs to. 将列定义为除其所属表以外的大量表上的外键也很常见。

With that in mind - and, due to time constraints - the following only handles primary keys, and I've only tested it on single-column primary keys: 考虑到这一点-并且由于时间限制-以下内容仅处理主键,而我仅在单列主键上对其进行了测试:

  SELECT c.COLUMN_NAME as '@Name',
        c.TABLE_NAME as '@Table',
        Data_type as '@DataType',
        character_octet_length as '@Length', case when tc.CONSTRAINT_NAME IS NULL then 'false' else 'true' end as '@IsPrimaryKey'
    FROM information_schema.COLUMNS c
        left outer join INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu on c.TABLE_NAME = kcu.TABLE_NAME and kcu.COLUMN_NAME = c.COLUMN_NAME
        left outer join  INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc on tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME and tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
    FOR XML PATH ('Column'), TYPE

For clarity, I've included the table name in the output. 为了清楚起见,我在输出中包括了表名。 Sample output: 样本输出:

<Column Name="AdministratorID" Table="Administrator" DataType="int"
    IsPrimaryKey="true" /><Column Name="UserName" Table="Administrator"
    DataType="varchar" Length="50" IsPrimaryKey="false" /><Column Name=
    ...

I realise this doesn't match your requirements exactly, but it should give you something to build upon. 我意识到这并不完全符合您的要求,但是它应该给您一些基础。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM