question

pizaro-9889 avatar image
0 Votes"
pizaro-9889 asked EchoLiu-msft commented

Update script to update a column on a Table


I need help with an update script. I want to write an update script that will update a column called lenderName in my table called Lender.



CREATE TABLE [dbo].[Lender](
[LenderCode] [VARCHAR](255) NOT NULL,
[LenderName] [VARCHAR](255) NOT NULL,
[CreateDate] [DATETIME] NOT NULL,
[LenderID] [NVARCHAR](255) NOT NULL
) ON [PRIMARY]


-----Insert Statement


INSERT INTO Lender(LenderCode,LenderName,CreateDate,LenderID)
VALUES ('W001','Wells Fargo Bank','2021-03-30 19:09:21.227','2'),
('W001','Wells Fargo Home Mortgage','2021-06-17 14:51:41.570','0011D00000FFF7ICAE'),
('P104','Mortgage Corporation','2021-03-30 19:09:21.227','212'),
('P104','PHH Mortgage Corporation','2021-06-17 14:51:41.570','0011D00000CMDv6PHD'),
('F145','First Bank','2021-03-30 19:09:21.227','390'),
('J346','Axia Financial','2021-03-30 19:09:21.227','320')


----After insert statement

132546-image.png


So what i want to do is, update the LenderName column that has same LenderCode with the LenderName that has max CreateDate and also with the lenderID column that is > 10 characters( that is len(lenderID) > 10


---final Result set after the update statement

132572-image.png


sql-server-transact-sql
image.png (28.2 KiB)
image.png (28.9 KiB)
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Could you please validate all the answers so far and provide any update?
If all of them are not working or helpful, please provide more sample data or details about your issue.
Please remember to accept the answers if they helped. Your action would be helpful to other users who encounter the same issue and read this thread.

Thank you for understanding!

0 Votes 0 ·

1 Answer

EchoLiu-msft avatar image
0 Votes"
EchoLiu-msft answered EchoLiu-msft edited

Hi @pizaro-9889,

Please check:

 ;WITH cte
 as(SELECT *
 ,MAX([CreateDate]) OVER(PARTITION BY [LenderCode]) mm
 FROM [dbo].[Lender]
 WHERE LEN([LenderID])>10)
    
 UPDATE t
 SET t.[LenderName]=c.[LenderName]
 FROM [dbo].[Lender] t
 JOIN cte c
 ON t.[LenderCode]=c.[LenderCode] 

Output:
132652-image.png


If you have any question, please feel free to let me know.


Regards
Echo


If the answer is helpful, please click "Accept Answer" and upvote it.



image.png (15.7 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.