How to I update a table column with a Join in Teradata? - join

I have the following two tables:
Transaction_table:
Date
SSN
Cust_Num
Cust_Ind
1/1/21
111-1111
null
null
1/2/21
222-2222
null
null
1/3/21
null
null
null
Customer_table:
Date
SSN
Cust_Num
Cust_Name
1/1/21
111-1111
101
Adam
1/2/21
222-2222
102
Bobby
1/3/21
333-3333
103
Carter
How do I update the Cust_Num on the Transaction_table with the Cust_Num on the Customer_table when the SSN on both table equal each other? Additionally, how do I update the Cust_Ind to ‘SSN Match’ when SSN on both table equal each other? Thank you!
I tried the following code and received errors:
Update t
from Transaction_table as t,
Customer_table as src
set t.Cust_Num = src.Cust_Num,
t.Cust_ind = 'SSN_Match'
where t.SSN = src.SSN

Related

FireDac, Master-Detail, set master PK as NEW_id in detail, Cached updates

I have 2 tables:
tbl1(idM int identity(1,1), Name nvarchar(50));
tbl2(idRow int identity(1,1), idM int, Data nvarchar(50));
They are queried via fdQuery1 and fdQuery2 (master:fdQuery1, masterfield:idM).
CachedUpdates = True on both fdQuery.
FDSchemaAdapter is connected to both also.
Also FDUpdateSQL1 and FDUpdateSQL2 connected to fdQuery1 and fdQuery2.
On inserting (fdQuery1.Insert) new row in fdQuery1 it's idM is shown as -2 by default, f.e.
FDUpdateSQL1 insert text:
INSERT INTO tbl1 (Name)
VALUES (:NEW_Name);
SELECT SCOPE_IDENTITY() AS idM
FDUpdateSQL2 insert text:
INSERT INTO tbl2 (idM, Data)
VALUES (:NEW_idM, :NEW_Data);
SELECT SCOPE_IDENTITY() AS idRow
On saving I execute this code:
FDSchemaAdapter.ApplyUpdates;
fdQuery1.CommitUpdates;
fdQuery2.CommitUpdates;
Target: fill form with DB-aware components connected to tbl1 and tbl2 and set tbl2.idM automatically.
How can I do this?
I tried OnUpdateRecord method but it still doesn't return idM from FDUpdateSQL1 insert.
fdQuery1.OnAfterPost field fdQuery1idM.asInteger also returns -2 value.
Current example result in tables:
tbl1
|idM|Name|
|--------|
|5 |Test|
tbl2
|idRow|idM|Data |
|------------------|
|10 |-2 |DataText|
Target tbl2
|idRow|idM|Data |
|------------------|
|10 |5 |DataText|
Thank you!

how to display name use LINQ

Actually i have two tables i want to display records of the use of second table. Please help me in this. Let me provide you example.
[TABLE1]
LocationID LoginID Location_Name
1 101 A
2 102 B
3 103 C
[TABLE2]
ID LoginID No_Of_Item Location ToLocation
1 101 5 1 2
2 102 6 2 3
3 103 7 1 3
This is my database. Now i want to show [TABLE2] records with location name. But i am unable to do that. Please help me in this LINQ Query.
This is my code.
public IQueryable<StockTransferViewModel> GetAllStockTransferDetailByLoginId(string LoginId)
{
var StockList = (from aspuser in context.AspNetUsers
join cus in context.Customers on aspuser.Id equals cus.LoginID
join transfer in context.StockTransfers on aspuser.Id equals transfer.LoginID
where transfer.LoginID == LoginId
select new StockTransferViewModel
{
ID = transfer.ID,
LoginID = transfer.LoginID,
Date_Of_Transfer = transfer.Date_Of_Transfer,
No_Of_Sku = transfer.No_Of_SKU,
FromLocationName=transfer.Location,
ToLocation=transfer.ToLocation,
}).AsQueryable();
return StockList;
}
If TABLE1 is named Locations, you'll likey want to add the following lines after the line starting with join transfer in:
join fromLocation in context.Locations on transfer.Location equals fromLocation.LocationID
join toLocation in context.Locations on transfer.Location equals toLocation.LocationID
Then in your select statement, you'll want:
FromLocationName = fromLocation.Location_Name,
ToLocation = toLocation.Location_Name,

DELPHI DBgrid Lookup

need help i have 2 tables below
tblA tblB
emp_no emp_no
cust_no emp_name
others....... cust_no
cust_name
in delphi i have dbgrid i create 2 lookup with
(1) ResultField = emp_name from tblB
keyfields = emp_no
lookupKeyfields = emp_no and
(2) lookupResultField cust_name from tblB
keyfields = emp_no
lookupKeyfields = emp_no
no problem on this but when i save using applyUpdate only the emp_no is saved to tblA i want to get also the cust_no of lookup and save also to tblA
what is the possible solution on this
thanks

Elegant linq solution for left joins with unique data

I woud like to inquire if my Linq solution below is a good solution or if there is a better way. I am new to using Linq, and am most familiar with MySQL. So I've been converting one of my past projects from PHP to .NET MVC and am trying to learn Linq. I would like to find out if there is a better solution than the one I came up with.
I have the following table structures:
CREATE TABLE maplocations (
ID int NOT NULL AUTO_INCREMENT,
name varchar(35) NOT NULL,
Lat double NOT NULL,
Lng double NOT NULL,
PRIMARY KEY (ID),
UNIQUE KEY name (name)
);
CREATE TABLE reservations (
ID INT NOT NULL AUTO_INCREMENT,
loc_ID INT NOT NULL,
resDate DATE NOT NULL,
user_ID INT NOT NULL,
PRIMARY KEY (ID),
UNIQUE KEY one_per (loc_ID, resDate),
FOREIGN KEY (user_ID) REFERENCES Users (ID),
FOREIGN KEY (loc_ID) REFERENCES MapLocations (ID)
);
CREATE TABLE Users (
ID INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
email VARCHAR(50) NOT NULL,
pass VARCHAR(128) NOT NULL,
salt VARCHAR(5) NOT NULL,
PRIMARY KEY (ID),
UNIQUE KEY unique_names (name),
UNIQUE KEY unique_email (email)
);
In MySQL, I use the following query to get the ealiest reservation at each maplocation with a non null date for any locations that don't have a reservation.
SELECT locs.*, if(res.resDate,res.resDate,'0001-01-01') as resDate, res.Name as User
FROM MapLocations locs
LEFT JOIN (
SELECT loc_ID, resDate, Name
FROM Reservations, Users
WHERE resDate >= Date(Now())
AND user_ID = Users.ID
ORDER BY resDate
) res on locs.ID = res.loc_ID
group by locs.ID
ORDER BY locs.Name;
In Linq, with Visual studio automatically creating much of the structure after connecting to the database, I have come up with the following equivalent to that SQL Query
var resList = (from res in Reservations
where res.ResDate >= DateTime.Today
select res);
var locAndRes =
(from loc in Maplocations
join res in resList on loc.ID equals res.Loc_ID into join1
from res2 in join1.DefaultIfEmpty()
join usr in Users on res2.User_ID equals usr.ID into join2
from usr2 in join2.DefaultIfEmpty()
orderby loc.ID,res2.ResDate
select new {
ID = (int)loc.ID,
Name = (string)loc.Name,
Lat = (double)loc.Lat,
Lng = (double)loc.Lng,
resDate = res2 != null ?(DateTime)res2.ResDate : DateTime.MinValue,
user = usr2 != null ? usr2.Name : null
}).GroupBy(a => a.ID).Select(b => b.FirstOrDefault());
So, I'm wondering is there a better way to perform this query?
Are these equivalent?
Are there any good practices I should be following?
Also, one more question, I'm having trouble getting this from the var to a List. doing something like this doesn't work
List<locAndResModel> locList = locAndRes.AsQueryable().ToList<locAndResModel>();
In the above snippet locAndResModel is just a class which has variables to match the int, string, double double, DateTime, string results of the query. Is there an easy way to get a list without having to do a foreach and passing the results to a constructor override? Or should I just add it to ViewData and return the View?
You'll want to take advantage of the automatic joins performed by the Entity Framework. Give this a try and let me know if it does what you want:
var locAndRes = from maplocation in MapLocations
let earliestReservationDate = maplocation.Reservations.Min(res => res.resDate)
let earliestReservation = (from reservation in mapLocation.Reservations
where reservation.resDate == earliestReservationDate && reservation.resDate >= DateTime.Today
select reservation).FirstOrDefault()
select new locAndResModel( maplocation.ID, maplocation.name, maplocation.Lat, maplocation.Lng, earliestReservation != null ? earliestReservation.resDate : DateTime.MinValue, earliestReservation != null ?earliestReservation.User.name : null)

Linq to Entity with multiple left outer joins

I am trying to understand left outer joins in LINQ to Entity. For example I have the following 3 tables:
Company, CompanyProduct, Product
The CompanyProduct is linked to its two parent tables, Company and Product.
I want to return all of the Company records and the associated CompanyProduct whether the CompanyProduct exists or not for a given product. In Transact SQL I would go from the Company table using left outer joins as follows:
SELECT * FROM Company AS C
LEFT OUTER JOIN CompanyProduct AS CP ON C.CompanyID=CP.CompanyID
LEFT OUTER JOIN Product AS P ON CP.ProductID=P.ProductID
WHERE P.ProductID = 14 OR P.ProductID IS NULL
My database has 3 companies, and 2 CompanyProduct records assocaited with the ProductID of 14. So the results from the SQL query are the expected 3 rows, 2 of which are connected to a CompanyProduct and Product and 1 which simply has the Company table and nulls in the CompanyProduct and Product tables.
So how do you write the same kind of join in LINQ to Entity to acheive a similiar result?
I have tried a few different things but can't get the syntax correct.
Thanks.
Solved it!
Final Output:
theCompany.id: 1
theProduct.id: 14
theCompany.id: 2
theProduct.id: 14
theCompany.id: 3
Here is the Scenario
1 - The Database
--Company Table
CREATE TABLE [theCompany](
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
CONSTRAINT [PK_theCompany] PRIMARY KEY CLUSTERED
( [id] ASC ) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
GO
--Products Table
CREATE TABLE [theProduct](
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
CONSTRAINT [PK_theProduct] PRIMARY KEY CLUSTERED
( [id] ASC
) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
GO
--CompanyProduct Table
CREATE TABLE [dbo].[CompanyProduct](
[fk_company] [int] NOT NULL,
[fk_product] [int] NOT NULL
) ON [PRIMARY];
GO
ALTER TABLE [CompanyProduct] WITH CHECK ADD CONSTRAINT
[FK_CompanyProduct_theCompany] FOREIGN KEY([fk_company])
REFERENCES [theCompany] ([id]);
GO
ALTER TABLE [dbo].[CompanyProduct] CHECK CONSTRAINT
[FK_CompanyProduct_theCompany];
GO
ALTER TABLE [CompanyProduct] WITH CHECK ADD CONSTRAINT
[FK_CompanyProduct_theProduct] FOREIGN KEY([fk_product])
REFERENCES [dbo].[theProduct] ([id]);
GO
ALTER TABLE [dbo].[CompanyProduct] CHECK CONSTRAINT
[FK_CompanyProduct_theProduct];
2 - The Data
SELECT [id] ,[value] FROM theCompany
id value
----------- --------------------------------------------------
1 company1
2 company2
3 company3
SELECT [id] ,[value] FROM theProduct
id value
----------- --------------------------------------------------
14 Product 1
SELECT [fk_company],[fk_product] FROM CompanyProduct;
fk_company fk_product
----------- -----------
1 14
2 14
3 - The Entity in VS.NET 2008
alt text http://i478.photobucket.com/albums/rr148/KyleLanser/companyproduct.png
The Entity Container Name is 'testEntities' (as seen in model Properties window)
4 - The Code (FINALLY!)
testEntities entity = new testEntities();
var theResultSet = from c in entity.theCompany
select new { company_id = c.id, product_id = c.theProduct.Select(e=>e) };
foreach(var oneCompany in theResultSet)
{
Debug.WriteLine("theCompany.id: " + oneCompany.company_id);
foreach(var allProducts in oneCompany.product_id)
{
Debug.WriteLine("theProduct.id: " + allProducts.id);
}
}
5 - The Final Output
theCompany.id: 1
theProduct.id: 14
theCompany.id: 2
theProduct.id: 14
theCompany.id: 3
IT should be something like this....
var query = from t1 in db.table1
join t2 in db.table2
on t1.Field1 equals t2.field1 into T1andT2
from t2Join in T1andT2.DefaultIfEmpty()
join t3 in db.table3
on t2Join.Field2 equals t3.Field3 into T2andT3
from t3Join in T2andT3.DefaultIfEmpty()
where t1.someField = "Some value"
select
{
t2Join.FieldXXX
t3Join.FieldYYY
};
This is how I did....
You'll want to use the Entity Framework to set up a many-to-many mapping from Company to Product. This will use the CompanyProduct table, but will make it unnecessary to have a CompanyProduct entity set in your entity model. Once you've done that, the query will be very simple, and it will depend on personal preference and how you want to represent the data. For example, if you just want all the companies who have a given product, you could say:
var query = from p in Database.ProductSet
where p.ProductId == 14
from c in p.Companies
select c;
or
var query = Database.CompanySet
.Where(c => c.Products.Any(p => p.ProductId == 14));
Your SQL query returns the product information along with the companies. If that's what you're going for, you might try:
var query = from p in Database.ProductSet
where p.ProductId == 14
select new
{
Product = p,
Companies = p.Companies
};
Please use the "Add Comment" button if you would like to provide more information, rather than creating another answer.
LEFT OUTER JOINs are done by using the GroupJoin in Entity Framework:
http://msdn.microsoft.com/en-us/library/bb896266.aspx
The normal group join represents a left outer join. Try this:
var list = from a in _datasource.table1
join b in _datasource.table2
on a.id equals b.table1.id
into ab
where ab.Count()==0
select new { table1 = a,
table2Count = ab.Count() };
That example gives you all records from table1 which don't have a reference to table2.
If you omit the where sentence, you get all records of table1.
Please try something like this:
from s in db.Employees
join e in db.Employees on s.ReportsTo equals e.EmployeeId
join er in EmployeeRoles on s.EmployeeId equals er.EmployeeId
join r in Roles on er.RoleId equals r.RoleId
where e.EmployeeId == employeeId &&
er.Status == (int)DocumentStatus.Draft
select s;
Cheers!
What about this one (you do have a many-to-many relationship between Company and Product in your Entity Designer, don't you?):
from s in db.Employees
where s.Product == null || s.Product.ProductID == 14
select s;
Entity Framework should be able to figure out the type of join to use.

Resources