从不同的表导入Postgres

时间:2019-12-05 00:17:07

标签: sql postgresql database-migration

我对Postgres还是很陌生。我有一个名为: @post('/project', { responses: { '200': { description: 'Plane model instance', content: { 'application/json': { schema: getModelSchemaRef(Project) } }, }, }) async create( @requestBody({ content: { 'application/json': { schema: getModelSchemaRef(PlaneWithRelations, { exclude: ['id'] }), }, }, }) plane: Omit<PlaneWithRelations, 'id'>, ): Promise<Plane> { const plane = await this.planeRepository.create({ name: plane.name }); for (const pilot of planes.pilots) { await this.pilotRepository.create({ ...pilot, planeId: plane.id }); } return plane; } 的表,其字段为:name,     国籍,缩写,形容词,人。

screenshot of table columns

我发现此sql查询可从以下位置插入数据:https://stackoverflow.com/a/21759321/9469766 以下查询片段。 如何更改查询以将这些值插入我的university_table表中     -创建并加载国籍表-英文

university_country

2 个答案:

答案 0 :(得分:1)

要将T-SQL转换为与Postres的SQL方言兼容,可以使用以下步骤。

  1. 删除所有方括号(在SQL标识符中它们是非法的)。如果您有要求使用双引号"的标识符,但我强烈建议您完全避免使用双引号(因此,在SQL中切勿使用"
  2. 删除所有GO语句并以;结束语句(对于SQL Server也是如此that is recommended
  3. 如果您未在Postgres中创建(通常不这样做),请删除[dbo].模式前缀。
  4. 删除Postgres中不需要的ON [Primary]选项(等效于定义一个表空间,但Postgres几乎不需要它)
  5. SQL(或Postgres)中没有IF,有条件地使用DROP TABLE IF EXISTS ...删除表。
  6. Postgres中没有聚集索引,因此只需将其设置为常规索引并删除WITH关键字引入的所有选项即可。
  7. 通过comment on定义表注释,而不是通过调用存储过程
  8. identity(x,y)需要替换为标准SQL generated always as identity
  9. 没有nvarchar类型,只需创建所有varchar并确保您的数据库是使用可存储多字节字符的编码创建的(默认情况下为UTF-8,因此应为很好)
  10. 不是必需的,但是:强烈建议使用snake_case标识符,而不是Postgres中的CamelCase

将所有脚本放在一起应该是这样的:

DROP TABLE IF EXISTS Nationality CASCADE;

CREATE TABLE nationality
(
    Nationality_id int generated always as IDENTITY NOT NULL,
    Country varchar(50) NULL,
    Abbreviation varchar(5) NULL,
    Adjective varchar (130) NULL,
    Person varchar (60) NULL
);

INSERT INTO Nationality (Country, Abbreviation, Adjective, Person )
VALUES  ( 'AMERICAN - USA','US','US (used attributively only, as in US aggression but not He is US)','a US citizen' ),
        ( 'ARGENTINA','AR','Argentinian','an Argentinian' ),
        ( 'AUSTRALIA','AU','Australian','an Australian' ),
        ( 'BAHAMAS','BS','Bahamian','a Bahamian' ),
        ( 'BELGIUM','BE','Belgian','a Belgian' );


CREATE INDEX idx_Nationality ON Nationality 
(
    Nationality_ID ASC,
    Country ASC
);

comment on table nationality is 'CreatedBy: Dan Flynn, Sr. SQL Server DBA
CreationDate: 02/12/2014

Nationality table contains five columns, i.e.:

1. NationalityID, 2. Country, 3. Abbreviation, 4. Adjective, 5. Person

IDs 1 to 34 are alphabetical countries that are statistically the most popular as far as interaction with the United States.  IDs 35 to 248 are also alphabetical for the rest of the countries.
';

我对没有定义主键感到惊讶。您可能要添加:

alter table nationality
   add primary key (nationality_id);

答案 1 :(得分:0)

有一个SQL标准,但是没有人完全实现它。某些数据库系统(如PostgreSQL)更擅长遵循标准,而其他数据库系统(如Microsoft SQL Server)则没有。

其结果是,您不能采用可在一个RDBMS上运行的SQL并与另一个RDBMS一起使用。您将不得不将其翻译为PostgreSQL方言。