SQL join table with a dynamic database name - tsql

I have a table which contains a employee ID and a database ID code in database DBX0 table 'FirstTable':
Employee ID
Database ID
123
1
456
2
789
2
149
3
The database name is stored in a different table 'databases' like :
Database ID
DB name
1
DBX1
2
DBX2
3
DBX3
So what I'm trying to do is join the first table with a separate table which is stored in the identified database, like
SELECT * from DBX0.dbo.FirstTable a join (SELECT [DB name] from DBX0.dbo.databases where [database ID] = a.[database ID]).dbo.OtherTable
(I don't think this will actually work with a subquery, but this would return the result that I want in theory.)
I have tried dynamic sql with a cursor to iterate through each database and then only return results based on database ID = database ID and Employee ID = Employee ID, but this returns the results in a separate result per database.
Also tried:
Select * from (SELECT * from DBX0.dbo.FirstTable a join '+#dbname+'.dbo.OtherTable on a.employeeid = b.employeeid and a.dbid = b.dbid)
in dynamic sql, but this didn't work either.
Is there any way to get all of the data in one result?

Related

Qr code scanner PostgreSQL Database Validation

I'm creating a very basic qr code scanner entrance database system with postgresql
2 tables:
Table "persons" include a list of all participants with: id, first_name, last_name, email, phone, qr_code
Table "check_ins" include a list of all the people who entered the event: id, person_id, check_in_time
I created this query:
INSERT INTO check_ins (person_id)
SELECT id
FROM persons
WHERE qr_code = {{ scanner1.data[0]}} AND
EXISTS (SELECT * FROM persons WHERE qr_code = {{ scanner1.data['0']}})
{{ scanner1.data[0]}} is the scanner input value
The query still work for qr_code that aren't present in table persons. I'm expecting an error (I have a popup that trigger if the query is a failure with a text "Qr Code Already scanned or Invalid")
I'm expecting this:
qr_code scanned present in table persons but not in table check_ins = insert in table check_ins | query run successfully
qr_code scanned not present in table persons = query failure
qr_code scanned present in table persons but also in table check_ins = query failure
I structured the app so when the query run successfully a text will appear with "Qr code valid" and when not "Qr code already scanned or invalid"
This query returns either the id of the new check_ins record or an empty resultset (nothing was inserted because either t CTE had no record in it or this person_id already existed in check_ins).
So you can distinguish success from failure by the result.
with t(pid) as
(
SELECT id FROM persons
WHERE qr_code = {{ scanner1.data['0']}}
)
INSERT INTO check_ins (person_id)
SELECT pid from t
WHERE NOT EXISTS (SELECT FROM check_ins WHERE person_id = t.pid)
RETURNING id;

How to get value of specific column on first table and insert into the second table in Spring boot JPA

I have a project I want to get data from a specific column from table one and insert those data by id to the specific column in table 2 what query could I use? how to get data from specific column from table 1 to a specific column to table 2
here's my Repository
#Query(value = "SELECT :refId FROM product WHERE id = :id", nativeQuery=true)
public String findReferenceid(#Param(value = "id") long id, #Param(value = "refId") String refId);
Thanks.

Entity Framework - query inside a where statement

I have a scenario where I need to fetch list of string values from a table.
I need to query the Subject table and get list of subjects:
EmployeeDetails emp = new EmployeeDetails();
emp.subjects = from x in EmpDB.subjects
join y in EmpDB.employeeInfo
on x.subjectCode equals y.subjectCode select new
{
x.subjectTitle,
}.toList();
I have an employee ID which I need to query the EmployeeDetails table and get SubjectCodes of that particular Employee ID, and using those subject codes, I need to query the Subject table and get the subject values.
I assume that in EmployeeDetails class you have property Subjects with List.
EmployeeDetails emp = new EmployeeDetails();
emp.subjects = (from x in EmpDB.subjects
join y in EmpDB.employeeInfo on x.subjectCode equals y.subjectCode
where y.EmployeeId = <<your ID>> // Employee ID you searching
select x.subjectTitle).ToList();

Native query to Laravel eloquent

Good day, I have 3 tables which is products, users, and pivot product_user table.
and I want to fetch all the data in the main table if that row contains a pivot data.
Example
products table
ID Name
1 sample 1----------> is in pivot table **product_user**
2 sample 2----------> is in pivot table **product_user**
3 sample 3
users table
ID Name
1 user1-------------> is in the pivot table **product_user**
2 user2
3 user3-------------> is in the pivot table **product_user**
product_user
product_id user_id
1 1
3 2
In this scenario how can I fetch the data in the two main table that contains pivot data?
How can I achieve the result of this query in laravel way?
SELECT p.`name`, u.`first_name`
FROM product_user AS pu
LEFT JOIN products AS p
ON pu.`product_id` = p.id
LEFT JOIN `users` AS u
ON pu.`user_id` = u.`id`
result
name first_name
sample 1 user firstname
You have a BelongsToMany relationship Product ↔ User:
class ProductUser extends Model {
public function product() {
return $this->belongsTo(Product::class);
}
public function user() {
return $this->belongsTo(User::class);
}
}
$pivots = ProductUser::with('product', 'user')->get();
foreach($pivots as $pivot) {
// $pivot->user->first_name
// $pivot->product->name
}

In DB2, perform an update based on insert for large number of rows

In DB2, I need to do an insert, then, using results/data from that insert, update a related table. I need to do it on a million plus records and would prefer not to lock the entire database. So, 1) how do I 'couple' the insert and update statements? 2) how can I ensure the integrity of the transaction (without locking the whole she-bang)?
some pseudo-code should help clarify
STEP 1
insert into table1 (neededId, id) select DYNAMICVALUE, id from tableX where needed value is null
STEP 2
update table2 set neededId = (GET THE DYNAMIC VALUE JUST INSERTED) where id = (THE ID JUST INSERTED)
note: in table1, the ID col is not unique, so i can't just filter on that to find the new DYNAMICVALUE
This should be more clear (FTR, this works, but I don't like it, because I'd have to lock the tables to maintain integrity. Would be great it I could run these statements together, and allow the update to refer to the newAddressNumber value.)
/****RUNNING TOP INSERT FIRST****/*
--insert a new address for each order that does not have a address id
insert into addresses
(customerId, addressNumber, address)
select
cust.Id,
--get next available addressNumber
ifNull((select max(addy2.addressNumber) from addresses addy2 where addy2.customerId = cust.id),0) + 1 as newAddressNumber,
cust.address
from customers cust
where exists (
--find all customers with at least 1 order where addressNumber is null
select 1 from orders ord
where 1=1
and ord.customerId = cust.id
and ord.addressNumber is null
)
/*****RUNNING THIS UPDATE SECOND*****/
update orders ord1
set addressNumber = (
select max(addressNumber) from addresses addy3
where addy3.customerId = ord1.customerId
)
where 1=1
and ord1.addressNumber is null
The IDENTITY_VAL_LOCAL function is a non-deterministic function that returns the most recently assigned value for an identity column, where the assignment occurred as a result of a single INSERT statement using a VALUES clause