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.
Lawrence SalvucciInformation Technology ManagerAsked:
Who is Participating?
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.
Russell FoxDatabase DeveloperCommented:
You could use a CTE:
; WITH YourTableUpdate
AS (
		, foo = 1 + 3
	FROM YourView
	SET foo = ytu.foo
FROM YourTable yt
	INNER JOIN YourTableUpdate ytu
		ON yt.RecordID = ytu.RecordID

Open in new window

Eugene ZCommented:
Pawan KumarDatabase ExpertCommented:
You need to use like below..

Update x
SET x.ColName1 = y.ColName1, x.ColName2=y.ColName2....etc
FROM TableName x
ON a.JoiningColumn = y.JoiningColumn
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.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.