BEGIN TRANSACTION SET QUOTED_IDENTIFIER ON SET ARITHABORT ON SET NUMERIC_ROUNDABORT OFF SET CONCAT_NULL_YIELDS_NULL ON SET ANSI_NULLS ON SET ANSI_PADDING ON SET ANSI_WARNINGS ON COMMIT BEGIN TRANSACTION GO ALTER TABLE dbo.Import_approval ADD JustWriteoffs numeric(18, 6) NULL, REMARK varchar(200) null GO ALTER TABLE dbo.Import_approval SET (LOCK_ESCALATION = TABLE) GO COMMIT update Import_approval set JustWriteoffs=0 IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vMsAppUsed]')) DROP VIEW [dbo].[vMsAppUsed] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE VIEW [dbo].[vMsAppUsed] AS select app_id,appweight,used,selected, appweight-used-usedweight-justwriteoffs remain, appweight-usedweight-used-selected-justwriteoffs canbeused from (select ap.id app_id,ap.[weight] as appweight,ap.usedweight, case when selected is null then 0 else selected end selected, case when used is null then 0 else used end used, case when justwriteoffs is null then 0 else justwriteoffs end justwriteoffs from import_approval ap left join (select T1.app_id,sum(T1.selected) selected,sum(T1.used) used from (select app_id, case cancellation when 0 then convert(numeric(18,6),[weight]) else 0.000000 end selected , case cancellation when 1 then convert(numeric(18,6),[weight]) else 0.000000 end used from import_appstate) T1 group by T1.app_id)T2 on T2.app_id=ap.id)T3 GO