Update Query in SQL Server using a View as source

I have a view that I want to use to update a field in a table. The view is pulling data from this table and then I am doing some calculations to change the values. Now I want to take that new value from the view and update it back into this table's field. How do I use a view as the source for a update query? This view is also joined with other tables because it needs other data to do these calculations. Just not sure how to write the update query to use the view as the source.
LVL 1
Lawrence SalvucciInformation Technology ManagerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Russell FoxDatabase DeveloperCommented:
You could use a CTE:
; WITH YourTableUpdate
AS (
	SELECT RecordID
		, foo = 1 + 3
	FROM YourView
	)
UPDATE yt
	SET foo = ytu.foo
FROM YourTable yt
	INNER JOIN YourTableUpdate ytu
		ON yt.RecordID = ytu.RecordID

Open in new window

0
EugeneZ ZhitomirskySQL SERVER EXPERTCommented:
0
Pawan KumarDatabase ExpertCommented:
You need to use like below..

Update x
SET x.ColName1 = y.ColName1, x.ColName2=y.ColName2....etc
FROM TableName x
INNER JOIN ViewName y
ON a.JoiningColumn = y.JoiningColumn
0
Vitor MontalvãoMSSQL Senior EngineerCommented:
Lawrence, the View is a logical table so there's no difference to use a View or a Table in an UPDATE statement. Just use the View name instead of a table name and you should be good to go with the Update.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Lawrence SalvucciInformation Technology ManagerAuthor Commented:
Thank you every one. I was able to get the update to work using the view in place of the table.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
SQL

From novice to tech pro — start learning today.