SQL Update One Table with Value from Another Table - sql-server

I have the following SQL statement -
SELECT e.*, i.CaseNo, c.Claimant, c.Defendant, c.ClientID
FROM tblExpenses AS e
INNER JOIN tblInvoices AS i ON e.InvNo = i.InvNo
INNER JOIN tblCases AS c ON i.CaseNo = c.CaseNo
which demonstrates the link between three tables.
tblInvoices has a primary key [InvNo] which is also a foreign key in tblExpenses thus linking each expense with the relevant invoice.
tblCases has a primary key [CaseNo] which is also a foreign key in tblInvoices, thereby linking each invoice to a particular case.
Finally each case in tblCases has a column called [ClientID] which identifies the client whom the invoice was sent to.
Now then, tblExpenses also has a foreign key [ClientID] but at present the column is not populated. What I want to do, is use the above links to populate [ClientID] in tblExpenses, with the [ClientID] from tblCases, via the aforementioned links.
However I am unclear how to rewrite my SELECT query in order to carry out this population of the [ClientID] column in tblExpenses.
Can anyone please assist?

You already have the sufficient select query to get the required information. You just need to convert it to an update query.
UPDATE e SET e.ClientID=c.ClientID
FROM tblExpenses AS e
INNER JOIN tblInvoices AS i ON e.InvNo = i.InvNo
INNER JOIN tblCases AS c ON i.CaseNo = c.CaseNo

Related

SQL Server - Trying to join 2 foreign keys from 1 primary key in a procedure

Trying to join 2 foreign keys from 1 primary key in a procedure: Its very hard for me, and I want to make a code that will be simple. sitting for hours of hours from evening until morning and didn't find any answer to this issue. very hard. In mySQL there is an answer on this site but it doesn't work.
I must insert the each primary key (there are 2 in two different tables) to different tables. I tried with the "view" option but it didn't work.
My procedure is to write a story and insert an image, each one of them has ID.
CREATE PROCEDURE UserStory
#UserID [INT],
#story [NVARCHAR] (120),
#img [VARCHAR](MAX)
AS
BEGIN
INSERT INTO dbo.Stories (StoryText)
VALUES (#story)
INSERT INTO dbo.Images (img)
VALUES (#img)
SELECT
imagesInStories.imgID3, imagesInStories.StoryID3,
Stories.imgID2, Users_Stories.ID2, Users_Stories.StoryID2
FROM
Images B3, Stories T1, Table_Users
INNER JOIN
imagesInStories G1 ON B3.imgID3 = G1.imgID
INNER jOIN
imagesInStories G2 ON B3.imgID2 = G2.imgI
END
Why does this code cause errors? erorr...could not be found (I'll use Stories T1 and Table_Users later) right now the error just ruin it all...lol
My mission here is to insert the primary to two foreign key from two different tables (could be more if so..) .
The tables I use:
[dbo].[Images] , [Table_Users], [dbo].[Stories], [Users_Stories],
[imagesInStories] each has those IDs.
If any complain, tell me and I'll fix the writing and question.
P.S
I changed each key to have it's own unique name as ID2 and ID3 not same as
Images.ID, Stories.ID and/or imagesInStories.imgID, Stories.imgID
Is it necessary?
Thanks
E.
if you have assign alias to a table, you must use that and can't use the table name anymore
SELECT
imagesInStories.imgID3, imagesInStories.StoryID3,
Stories.imgID2, Users_Stories.ID2, Users_Stories.StoryID2
FROM
Images B3, Stories T1, Table_Users
INNER JOIN
imagesInStories G1 ON B3.imgID3 = G1.imgID
INNER jOIN
imagesInStories G2 ON B3.imgID2 = G2.imgI
so in the above query imagesInStories.imgID3 should be either G1.imgID3 or G2.imgID3
and the other column also.
Note : please avoid the comma notation in FROM and use proper ANSI JOIN style

Basic SQL - What’s best possible answer if you know ?

In SQL Server, you have a Customer table and an Order table. The relationship between the two tables is the CustomerId field. It’s a foreign key from the Orders back to the primary table Customer. With that in mind, how would you write a query that would retrieve Customers that don’t have Orders.
The following will return all customers on the left of the query and will show a NULL on the right where there are no matching order records.
We then filter to only show those with NULL in the right table.
SELECT *
FROM Customers c
LEFT JOIN Orders o
ON c.CustomerId = o.CustomerId
WHERE o.CustomerId IS NULL
Below is a great diagram explaining the different types of join

SQL Server - How to determine shared key between 2 tables?

For example, if I want to link OPOR, ORDR & ODLN but do not know what the common key between them is, how can I find this out?
Example:
SELECT o0.NumAtCard 'Customer PO'
, o0.DocNum 'Sales Order No'
, o1.DocNum 'Purchase Order No'
, o2.DocNum 'Delivery Order No'
, o0.DocTotal 'Total Price'
FROM ORDR o0
JOIN OPOR o1 ON o0.primarykey = o1.foreignkey -- left?
JOIN ODLN o2 ON o1.primarykey = o2.foreignkey -- inner?
How do I determine what the "primarykey" and "foreignkey" is?
OPOR's table structure:
ODLN table structure:
If you scroll down your sp_help results, you should see constraint. If there is a primary key constraint, look at what key it uses. The primary key is usually the one used to linked to another table.
You need to know the structure of the two tables. In SQL server:
sp_help TableA;
sp_help TableB;
In MySQL:
describe TableA;
describe TableB;
This will show you the table structure. If the database is designed well, you should be able to tell which columns are the foreign keys.
As far as knowing which columns to join on based on the results you posted:
1) You might be expecting something that isn't there.
2) It can depend on what you want to do. Suppose you want to match rows in OPOR to ODLN where they are marked as cancelled in ODLN, you would go:
select * from OPOR
inner join ODLN on
OPOR.DocEntry=ODLN.DocEntry
where CANCELLED='true';
or whatever a valid value for cancelled is. But without knowing your desired query or understanding more about the meaning of these columns, I can't really advise. The tables appear to be exactly the same which suggests it would be unusual to join them.

SQL View Optimization

I am trying to build a view that does basically 2 things, whether a record in table 1 is in table 2 and whether a link to another table is still there. it worked on a subset of data, but when i tried to run the full query it timed out in the view designer.
The view worked fine until I added in the check to see whether the link to another table was present.
Initially it joined table A to Table B and filtered out where A.ID wasnt present in the ID column in table B
I was then told that if the link between the person and the address table (stored in table C) was removed then we would have no way of knowing other than to get a full extract of that table again and see which links are no longer present. I am trying to use that check to determine whether to display some data in particular columns
I am using the following structure close to 60 times to choose whether to show information in a column:
Column1 = case when exists (select LinkID from LinkTable C
where cast(C.LinkAddressID as varchar) = A.AddressID
and cast(C.LinkID as varchar) = A.ID)
then Column1
else NULL
end
There is about 1.6m records in Table A just over 4m records in the Link table.
is there a better way to write this query / view that would be more optimized?
Please let me know if more information is needed
Select C.LinkID
From A
Left Join C On C.LinkAddressID = A.AddressID And C.LinkID = A.ID
This will give you C.LinkID if a match exists on the two conditions and NULL if both criteria are not satisfied.
Having indexes / keys such as primary key on A.ID and foreign key relationships based on what is in the join clause will provide very good performance.
As Joe suggested, if for all 60 columns you use the same AddressId and Id fields to match two tables, I believe so you can use something as following query
SELECT
Column1 = CASE WHEN C.LinkID IS NULL THEN NULL ELSE A.Column1 END,
....
FROM A
Left Join LinkTable C
ON C.LinkAddressID = A.AddressID AND C.LinkID = A.ID
Casting data types will definitely disable the advantage from index. So keep away data type cast if possible on joins and in WHERE clauses

Does not have a primary key defined and no valid primary key could be inferred

I have this query in making my view but the problem is this view is not included in my Model. So, I could not use this view.
Here is my code:
CREATE VIEW [dbo].[Payment_Transaction_vw]
AS
SELECT
id = ROW_NUMBER() OVER (ORDER BY (SELECT NULL)),
Transaction_Info.trans_name, Student_Info.ID_Number,
Student_Info.student_fname, Student_Info.student_lname,
SUM(Payment_Transaction.amount) AS amount
FROM
[Payment_Transaction]
INNER JOIN
Student_Info ON Payment_Transaction.student_info_id = Student_Info.student_info_id
INNER JOIN
Transaction_Info ON Payment_Transaction.trans_info_id = Transaction_Info.trans_info_id
GROUP BY
ID_Number, student_lname, student_fname, trans_name;
This view can be seen in the database after I create this. But not when I add a model. This is not included in my Entity.
Here is the error will displayed:
dbo.Payment_Transaction_vw does not have a primary key defined and no valid primary key could be inferred. This table/view has been excluded. To use the entity, you will need to review our schema, add the correct keys, and uncomment it.
Please help me with this matter. Thanks in advance.
I think it might be because EF has a hard time choosing the correct primary key. A way to force EF to choose a key of your liking seems to be to use ISNULL() for the primary key, and NULLIF() for the other columns (at least the ones that could cause confusion, like primary keys from other tables or non-nullable columns).
In your case this would mean:
SELECT
ISNULL(ROW_NUMBER() OVER(ORDER BY (SELECT NULL)), -1) AS Id,
NULLIF(Transaction_Info.trans_name,'') AS trans_name,
NULLIF(Student_Info.ID_Number,-1) AS ID_Number,
NULLIF(Student_Info.student_fname,'') AS student_fname,
NULLIF(Student_Info.student_lname,'') AS student_lname,
NULLIF(SUM(Payment_Transaction.amount),-1) AS amount
FROM [Payment_Transaction]
INNER JOIN Student_Info ON
Payment_Transaction.student_info_id = Student_Info.student_info_id
INNER JOIN Transaction_Info ON
Payment_Transaction.trans_info_id = Transaction_Info.trans_info_id
GROUP BY ID_Number, student_lname, student_fname, trans_name;
You probably don't need all these NULLIF()'s, but since I'm not sure what column is causing issues it's better to take all. If it works with this code, you can start removing the NULLIF from student names and trans_name.
You need to define first id column primary key mvc does not allow this when you are using it with model

Resources