Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge temp table as source table #959

Open
randomGitBeing132 opened this issue Apr 23, 2024 · 2 comments
Open

Merge temp table as source table #959

randomGitBeing132 opened this issue Apr 23, 2024 · 2 comments
Labels
api Related to library's API mssql Related to MS SQL Server (MSSQL) question Further information is requested

Comments

@randomGitBeing132
Copy link

Is there a way to use temp table as the source table in merge statement something like this?

await db.mergeInto('mainTable').using('tempData', 'mainTable.itemCode', 'tempData.itemCode').whenMatched()......

SQL Statement
MERGE INTO MainTable AS Target USING #TempData AS Source ON Target.ID = Source.ID WHEN MATCHED THEN UPDATE SET Target.Name = Source.Name WHEN NOT MATCHED THEN INSERT (ID, Name) VALUES (Source.ID, Source.Name);

Dialect: MSSQL

@igalklebanov
Copy link
Member

Hey 👋

AFAIK, the temporary table has to be defined first, either inside the same SQL procedure/function OR within the same request to database (${query that defines the temp table}; ${merge into query}).

Then you can add the temporary table to database context before invoking the merge query as follows:

db
  .withTables<{
    "#tempData": {
      ID: string;
      itemCode: string | null;
      Name: string;
    };
  }>()
  .mergeInto("MainTable as Target")
  .using("#tempData as Source", "Target.ID", "Source.ID")
  .whenMatched()
  .thenUpdateSet((eb) => ({
    Name: eb.ref("Source.Name"),
  }))
  .whenNotMatched()
  .thenInsertValues((eb) => ({
    ID: eb.ref("Source.ID"),
    Name: eb.ref("Source.Name"),
  }))

https://kyse.link/rIW7a

Lemme know if mssql yells about "#tempData".

@igalklebanov igalklebanov added question Further information is requested api Related to library's API mssql Related to MS SQL Server (MSSQL) labels Apr 23, 2024
@randomGitBeing132
Copy link
Author

randomGitBeing132 commented Apr 26, 2024

When trying to insert value into temp table it throws this error

RequestError: Invalid object name '#temp_table'.

await db.schema.createTable('#tempTable').addColumn('testCol', 'bigint').execute();
const tempDb = db.withTables<{
  '#tempTable': {
    testCol: number;
  };
}>();
await tempDb
  .insertInto('#tempTable')
  .values({
    testCol: 1234010001,
  })
  .execute();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api Related to library's API mssql Related to MS SQL Server (MSSQL) question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants