SQL Server视图 - 派生日期列

时间:2013-12-17 20:04:22

标签: sql-server view

我使用Employee表中的2列创建了一个视图,如下所示

Create VIEW [dbo].[vwTestEmp] AS 
   select 
       EMpID,
       case when (Address1 IS null) then null
            when (Address1 IS not null) then Address1
       end as "EMpAddress",
       '' as "Date_Verified" 
   FROM Employee;

现在Date_Verified不在Employee表中,因此视图中的派生列包含null。手动验证某些流程后,我想打电话

update [dbo].[vwTestEmp] 
set Date_verified = GETDATE() 
where EMpid = 60;

我收到错误

  

更新或插入视图或函数'vwTestEMp'失败,因为它包含派生或常量字段。

如何处理此错误?

感谢 MR

3 个答案:

答案 0 :(得分:2)

您无法通过Date_Verified的常量值更新视图。将查询更改为:

CREATE VIEW [dbo].[vwTestEmp1] AS 
    SELECT EMpID, Address1 AS EMpAddress], [Date_Verified] 
        FROM EMployee;

这样可以避免不必要的CASE,并将日期列的常量值替换为基础列。

此更新如SqlFiddle

所示

答案 1 :(得分:0)

您有错误。正确的语法是:

UPDATE < view_name > SET<column1>=<value1>,<column2>=<value2>,... WHERE <condition>;

答案 2 :(得分:0)

使用表格。

select 
    EMpID,
    Address1 as "EMpAddress",
    '' as "Date_Verified"
INTO [dbo].[tblTestEmp]
FROM Employee;

update [dbo].[tblTestEmp] 
set Date_verified = GETDATE() 
where EMpid = 60;