update table with values from 2 other tables - sql-server

I would like to find the nearest Employee for my Customer and update in order table. I tried a Query which throws an error. Can any one suggest what am doing wrong on my query? The only select Statement is working fine. But the update looks some thing wrong.
I have 3 tables
Customer_Master
Customer_ID Customer_Name WHID Cust_Location
Cust100001 Subash WH10001 0xE6100000010C1B2E724F57172A408449F1F109685340
Cust100002 Naresh WH10002 0xE6100000010CBE30992A18152A4093AAED26F8675340
Employee_Master
Emp_ID Emp_name WHID Emp_Location
Emp100001 Prakash WH10001 0xE6100000010C363B527DE7172A4069C36169E0675340
Emp100002 Suresh WH10002 0xE6100000010C98C3EE3B86172A4064E597C118685340
Emp100003 Vincent WH10001 0xE6100000010CE5B8533A58172A4090DD054A0A685340
Emp100004 Paul WH10002 0xE6100000010C2EE6E786A6142A40A0A696ADF5675340
Order_Tran
Order_ID Cust_ID Emp_ID
ORD19847 Cust100001 ?????
ORD19856 Cust100002 ?????
I have Location of the customer and also Employee in Master Tables. Now i want to update Emp_ID in Order_Tran table who is nearest to the customer location in Order Table for Customer Cust100001.
I tried the below query which is showing error
Update Order_Tran Set Emp_ID=(Select Top (1) Emp_ID, Employee_Master.Emp_Location.STDistance(Customer_Master.Cust_Location) AS DistanceApart FROM Customer_Master, Employee_Master WHERE Customer_ID = 'Cust100001'
and Customer_Master.WHID = Employee_Master.WHID ORDER BY DistanceApart);

Try selecting a single value in your sub-query (to stop the error) and adding an outer where clause (to ensure only the specified employee is updated).
UPDATE Order_Tran
SET Emp_ID=(SELECT TOP (1) Emp_ID
FROM Customer_Master, Employee_Master
WHERE Customer_ID = 'Cust100001'
AND Customer_Master.WHID = Employee_Master.WHID
ORDER BY Employee_Master.Emp_Location.STDistance(Customer_Master.Cust_Location))
WHERE Customer_ID = 'Cust100001'

Related

Replacing data in one table with data in another table using a unique ID

I'm using Access 2016 to view data from a table on our SQL server. I have a massive audit log where the record being viewed is represented by a "FolderID" field. I have another table that has values for the FolderID (represented as "fid") along with columns identifying the record's name and other ID numbers.
I want to be able to replace the FolderID value in the first table with CUSTOMER_NAME value from the second table so I know what's being viewed at a glance.
I've tried googling different join techniques to build a query that will accomplish this, but my google-fu is weak or I'm just not caffeinated enough today.
Table 1.
EventTime EventType FolderID
4/4/2019 1:23:39 PM A 12345
Table 2
fid acc Other_ID Third_ID CUSTOMER_NAME
12345 0 9875 12345678 Doe, John
Basically I want to query Table 2 to search for fid using the value in Table 1 for FolderID, and I want it to respond with the CUSTOMER_NAME associated with the FolderID/fid. The result would look like:
EventTime EventType FolderID
4/4/2019 1:23:39 PM A Doe, John
I'm stupid because I thought I was too smart to use the freaking Query Wizard. When I did, and it prompted me to create relationships and actually think about what I was doing, it came up with this.
SELECT [table1].EventTime, [table1].EventType, [table1].FolderID, [table1].ObjRef, [table1].AreaID, [table1].FileID, [table2].CUSTOMER_NAME, [table2].fid FROM [table2]
LEFT JOIN [table1] ON [table2].[fid] = [table1].[FolderID];
You can run this query and check if it helps!.
Select EventTime, EventType , CUSTOMER_NAME AS FolderID FROM Table1, Table2 Where Table1.FolderID = Table2.fid;
Basically, 'AS' is doing what you want here as you can rename your column to whatever you want.

UPDATE query to synchronize duplicated records

I have a number of duplicate records in a table, highly simplfied example is:
name, emailaddress, importantid
John Smith, john#smith.com, NULL
John Smith, john#smith.com, 12345
John Smith, john#smith.com, NULL
The problem comes later when another table is joined to this, it may be joined to one of the records which doesn't have the importantid I need.
I'm looking to update the table so that for each email address it finds the first one where importantid is not null and then updates the other records with that id, so all duplicate accounts end up having the important id.
How could I do that?
Thanks
SQL Fiddle Demo
UPDATE a
SET a.importantid = b.importantid
FROM test AS a
JOIN (SELECT emailaddress, max(importantid) as importantid
FROM test
GROUP BY emailaddress) AS b
ON a.emailaddress = b.emailaddress;
UPDATE yourTable t1
SET importanid =(SELECT max(importantid)
FROM yourTable t2
WHERE t2.emailaddress = t1.emailaddress AND t1.importantid is null and t2.importantid is not null)

spx for moving values to new table

I am trying to create one spx which based upon my ID which is 1009 will move 9 columns data to new table:
The old table has 9 columns:
CD_Train
CD_Date
CD_Score
Notes_Train
Notes_Date
Notes_Score
Ann_Train
Ann_Date
Ann_Score
userid - common in both tables
ID - 1009 - only exists in this table
and my new table has:
TrainingID,
TrainingType,
Score,
Date,
Status,
userid
TrainingType will have 3 values: Notes, CD, Ann
and other fields like score will get data from notes_score and so on
and date will get data from notes_date,cd_date depending upon in which column cd training went
status will get value from Notes_Train, cd_train and so on
based upon this, I am lost how should I do it
I tried querying one sql of users table and tried to do the join but I am losing the ground how to fix it
No idea yet, how to fill your column trainingId but the rest can be done by applying some UNION ALL clauses:
INSERT INTO tbl2 (trainingType,Date,Score,Status,userid)
Select 'CD' , CD_date, CD_score, CD_Train, userid FROM tbl1 where CD_date>0
UNION ALL
SELECT 'Notes', Notes_Date, Notes_Score, Notes_Train, userid FROM tbl1 where Notes_date>0
UNION ALL
SELECT 'Ann', Ann_Date, Ann_Score, ANN_Train, userid
FROM tbl1 where Ann_date>0
I don't know as yet whether all columns are filled in each row. That is the reason for the where clauses which should filter out only those rows with relevant data in the three selected columns.

SQL Script: Updating a column with another table pivoting on an ID

I have two SQL Server tables: ORDERS and DELIVERIES.
I would like to update the ORDERS table with a value from DELIVERIES. The ORDERS PK (OrderID) is common to both tables. Also, I would like to restrict the action to a specific CustomerID (within ORDERS).
ORDERS table:
OrderID | AccountID | AnalysisField1
DELIVERIES table:
DeliveryID | OrderID | AddressName
I want to update ORDERS.AnalysisField1 with the value from DELIVERIES.AddressName (linked by OrderID) but only where ORDERS.AccountID = '12345'
Please help. JM
Then try to use something like this:
UPDATE dbo.Orders
SET AnalysisField1 = d.Addressname
FROM dbo.Deliveries d
WHERE
d.OrderID = dbo.Orders.OrderID
AND dbo.Orders.AccountID = '12345'
If your AccountID column is of a numerical type (which the ID suffix would suggest), then you should not put unnecessary single quotes around the value in the WHERE clause:
AND dbo.Orders.AccountID = 12345

How to automatically set the SNo of the row in MS SQL Server 2005?

I have a couple of rows in a database table (lets call it Customer). Each row is numbered by SNo, which gets automatically incremented by the identity property inherent in MS SQLServer. But when I delete a particular row that particular row number is left blank, but I want the table to auto correct itself.
To give you a example:
I have a sample Customer Table with following rows:
SNo CustomerName Age
1 Dani 28
2 Alex 29
3 Duran 21
4 Mark 24
And suppose I delete 3rd row the table looks like this:
SNo CustomerName Age
1 Dani 28
2 Alex 29
4 Mark 24
But I want the table to look like this:
SNo CustomerName Age
1 Dani 28
2 Alex 29
3 Mark 24
How can I achieve that?
Please help me out
Thanks in anticipation
As has been pointed out doing that would break anything in a relationship with SNo, however if your doing this because you need ordinal numbers in you presentation layer for example, you can pull off a [1..n] row number with;
SELECT ROW_NUMBER() OVER(ORDER BY SNo ASC), SNo, CustomerName, Age FROM Customer
Obviously in this case the row number is just an incrementing number, its meaningless in relation to anything else.
I don't think you want to do that. Imagine the scenario where you have another table CustomerOrder that stores all customer orders. The structure for that table might look something like this:
CustomerOrder
-------------
OrderID INT
SNo INT
OrderDate DATETIME
...
In this case, the SNo field is a foreign key into the CustomerOrder table, and we use it to relate orders to a customer. If you delete a record from your Customer table (say with SNo = 1), are you going to go back and update the SNo values in the entire CustomerOrder table? It's best to just let the ID's autoincrement and not worry about spaces in the IDs due to deletions.
Why not create a view?
CREATE VIEW <ViewName>
AS
SELECT
ROW_NUMBER() OVER(ORDER BY SNo ASC) AS SNo
,CustomerName
,Age
FROM Customers
GO
Then access the data in customers table by selecting from the view.
Of course the SNo shown by the view has no meaning in the context of relationships, but the data returned will look exactly like you want it to look.
Using transactions when inserting records in the Database with C#
You have to use DBCC CHECKIDENT(table_name, RESEED, next_val_less_1);
As have been pointed out in other answers, this is a bad idea, and if the reason is for a presentation there are other solutions.
-- Add data to temp table
select SNo, CustomerName, Age
into #Customer
from Customer
-- Truncate Customer
-- Resets identity to seed value for column
truncate table Customer
-- Add rows back to Customer
insert into Customer(CustomerName, Age)
select CustomerName, Age
from #Customer
order by SNo
drop table #Customer

Resources