【问题标题】:Convert inline query to a query in TypeORM将内联查询转换为 TypeORM 中的查询
【发布时间】:2021-12-13 11:32:00
【问题描述】:

我需要转换这个 SQL 查询:

DECLARE @user AS dsschema.user_tools; 
INSERT INTO @user VALUES('`+ body.user_id+`','`+ body.tool_id+`'); 
EXECUTE dsschema.sp_user_tool @user

到 TypeORM createQueryBuilder();

有人可以帮帮我吗?

我尝试了以下方法,但遇到了以下问题:

Must declare the scalar variable @user:

Service.ts

class UserTools{
constructor(@InjectRepository(User) private userRepo: Repository:<User>)

 async insertUserData(body){
  try {
     const result = await this.manager.query(`DECLARE @user AS dsschema.user_tools`);
     const querybuilderResult = await this.userRepo.createQueryBuilder()
       .insert().into(@user).values({user_id: body.user_id, tool_id: body.tool_id});
     const spResult = await this.manager.query(`dsschema.sp_user_tool @user`);
     return spResult;
  } catch
  {
    throw error;
   }
 }
}

user.entity.ts

import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    user_id: string;

    @Column()
    tool_id: string;

}

【问题讨论】:

    标签: sql typescript nestjs typeorm


    【解决方案1】:

    首先,@PrimaryGeneratedColumn() 默认使用自动递增整数,这意味着在您的情况下,user_id 将是 number 类型,而不是 string。你可以在TypeORM Docs找到更多关于装饰器的信息:

    @PrimaryGeneratedColumn() 创建一个主列,该列的值将使用自动递增值自动生成。它将使用auto-increment/serial/sequence/identity 创建int 列(取决于提供的数据库和配置)。

    除此之外:

    1. 在您尝试单独执行 3 条指令时,这意味着当您运行插入语句时,@user 上下文不再可用。
    2. 表名由 TypeORM 引用,这意味着它将尝试插入到"@user" 而不是@user。 SQL 服务器将使用Invalid object name '@user' 拒绝此操作。

    你可以这样做:

    // This is the variable where the
    // user_tools table will be stored
    const userVariable = '@user';
    
    // getQueryAndParameters() returns an array with
    // two items, the query and the parameters.
    //
    // In this case:
    // [
    //   'INSERT INTO "@user"("user_id", "tool_id") VALUES (@0, @1)',
    //   [ 123, 'abc' ]
    // ]
    //
    const insertStatement = this.userRepo
      .createQueryBuilder()
      .insert()
      .into(userVariable)
      .values({
        user_id: 123,
        tool_id: 'abc',
      })
      .getQueryAndParameters();
    
    // Here we execute the statements in the same batch
    // to address [1]
    // For [2] we have to unescape your variable 
    // name @user (which is currently the quoted "@user") 
    await this.userRepo.query(
      `
      DECLARE ${userVariable} AS dsschema.user_tools;
      ${insertStatement[0].replace(`"${userVariable}"`, userVariable)};
      EXECUTE dsschema.sp_user_tool ${userVariable};
      `,
      insertStatement[1]
    );
    

    【讨论】:

      猜你喜欢
      • 2023-01-20
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 2020-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多