3

I have this view :

Create View View1 
AS 
Select F1,F2,0 As F3
From TB1

GO 

Update View1 Set F3=1

These commands raise this error :

Update or insert of view or function 'view1' failed because it contains a derived or constant field.

Is there any solution for updating "F3" field?

Thank you

Sachin
  • 40,216
  • 7
  • 90
  • 102

3 Answers3

5

The only way to change the value of a constant column in a view, is to alter the view itself. It does not make sense to run UPDATE statements on a constant or calculated column on a view, as the value is not stored physically in any table. Therefore, you have to do something like this:

ALTER VIEW View1 A
Select F1,F2,1 As F3
From TB1

Now, you could be tempted to put this code into a Stored Procedure. Unfortunately, this is not possible either, since DDL statements are not allowed in Stored Procedures. Another solution is therefore to store the value of column F3 in a separate table and change the view definition to bring the value into the view:

CREATE TABLE F3Column (
    Value AS int
)

go

INSERT F3Column VALUES (0)

go

CREATE VIEW View1 AS
select F1, F2, Value AS F3
from TB1, F3Column

go

-- This will allow you to change the value directly on the view:
UPDATE View1 SET F3 = 1

Just make sure that your F3Column-table always contains exactly 1 record. If it doesn't contain any records, View1 will always be empty. If it contains more than 1 record, View1 will give you duplicates.

Community
  • 1
  • 1
Dan
  • 10,480
  • 23
  • 49
1

F3 is not a column in any table, that's why you cannot update the value. Either you need to add it to your table or just display it as a new value in some conditions using CASE

CASE WHEN [condition goes here] THEN 1 END
sqluser
  • 5,502
  • 7
  • 36
  • 50
0

I think you want a result that shows 1 as F3 in your results like this:

SELECT F1, F2, 1 As F3
FROM View1

Or make a new view like this:

Create View View2 
AS 
Select F1, F2, 1 As F3
From TB1    
GO 
shA.t
  • 16,580
  • 5
  • 54
  • 111