根据更新

时间:2015-08-10 18:23:29

标签: sql-server sql-server-2008 stored-procedures

我在SQL Server 2008中有一个SQL表,为此目的包括
Patient_id(主要),Custno(Char),Recip_Id(Int)

1 - C01731 -    1  
2 - C01731 -    2  
3 - C01731 -    3  
4 - C01732 -    1  
5 - C01732 -    2  
6 - C01732 -    3  
7 - C01732 -    4  
8 - C01733 -    1  
9 - C01733 -    2

所以我用来移动基本上重新分配Custno的记录的存储过程如下......

ALTER PROCEDURE [dbo]。[JR_SP_BatchMovePatients]

@IDs tblDeletePatients Readonly,
@CustnoTo varchar(max)

AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

DECLARE @rownum int
IF EXISTS(SELECT * FROM UsersMailingData WHERE custno = @CustnoTo)
SET @rownum = (select MAX(recip_id)+1 FROM UsersMailingData WHERE custno = @CustnoTo);
ELSE
SET @rownum = 0;

-- Insert statements for procedure here
With Summary AS (
Select UsersMailingData.Patient_id, 
        UsersMailingData.custno,
        UsersMailingData.Recip_id, 
        row_number() over (order by Custno)+@rownum AS NewNum   
FROM UsersMailingData
WHERE Patient_ID IN (Select Patient_id FROM  @IDs))
UPDATE Summary
SET Custno = @CustnoTo, Recip_id = NewNum
END

但是因为我不能以这种方式使用row_number(),所以我很难完成这项任务。所以我传递了一个Patient_id表,它与我想要更新的Patient_id匹配,我需要将Custno字段更新为@CustnoTo值,同时根据@CustnoTo值中的最高Recip_id重新分配Recip_id。

因此,如果我将C01732移至C01731,结果将如下......

1 -  C01731 -    1
2 -  C01731 -    2
3 -  C01731 -    3
4 -  C01731 -    4
5 -  C01731 -    5
6 -  C01731 -    6
7 -  C01731 -    7 
8 -  C01733 -    1
9 -  C01733 -    2

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下查询的组合:

update UsersMailingData
set Custno=@CustnoTo
where Custno=@oldCustno

update u
    set recip_id=r
(select recip_id,row_number() over (partition by Custno order by Patient_id) as r from UsersMailingData )u

你的Sp应该像

CREATE PROCEDURE [dbo].[JR_SP_BatchMovePatients]

@oldCustno varchar(max),
@CustnoTo varchar(max)

AS
BEGIN
 SET NOCOUNT ON;

update UsersMailingData
set Custno=@CustnoTo
where Custno=@oldCustno

   update u
    set recip_id=r
(select recip_id,row_number() over (partition by Custno order by Patient_id) as r from UsersMailingData )u

END