我有一个存储两个值的表;每个客户的“总计”和“欠”。使用两个文件将数据上传到表中,一个带入“total”,另一个带入“owing”。这意味着我对每个 customerID 有两条记录:
customerID:--------Total:--------- Owing:
1234---------------- 1000----------NULL
1234-----------------NULL-----------200
我想编写一个将两条记录合并在一起的存储过程:
customerID:--------Total:--------- Owing:
1234---------------- 1000----------200
我见过使用 COALESCE 的例子,所以把这样的东西放在一起:
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
--Variable declarations
DECLARE @customer_id varchar(20)
DECLARE @total decimal(15,8)
DECLARE @owing decimal(15,8)
DECLARE @customer_name_date varchar(255)
DECLARE @organisation varchar(4)
DECLARE @country_code varchar(2)
DECLARE @created_date datetime
--Other Variables
DECLARE @totals_staging_id int
--Get the id of the first row in the staging table
SELECT @totals_staging_id = MIN(totals_staging_id)
from TOTALS_STAGING
--iterate through the staging table
WHILE @totals_staging_id is not null
BEGIN
update TOTALS_STAGING
SET
total = coalesce(@total, total),
owing = coalesce(@owing, owing)
where totals_staging_id = @totals_staging_id
END
END
有任何想法吗?