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?
 
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
 
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
 
Eugene ZCommented:
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
 
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
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.