如何通过Row_Number更新列,每行的值不同?

时间:2012-12-14 18:05:49

标签: sql sql-server stored-procedures sql-update row-number

我现在有这张桌子

CREATE TABLE [dbo].[DatosLegales](
    [IdCliente] [int] NOT NULL,
    [IdDatoLegal] [int] NULL,
    [Nombre] [varchar](max) NULL,
    [RFC] [varchar](13) NULL,
    [CURP] [varchar](20) NULL,
    [IMSS] [varchar](20) NULL,
    [Calle] [varchar](100) NULL,
    [Numero] [varchar](10) NULL,
    [Colonia] [varchar](100) NULL,
    [Pais] [varchar](50) NULL,
    [Estado] [varchar](50) NULL,
    [Ciudad] [varchar](50) NULL,
    [CodigoPostal] [varchar](10) NULL,
    [Telefono] [varchar](13) NULL,
    [TipoEmpresa] [varchar](20) NULL,
    [Tipo] [varchar](20) NULL,
 CONSTRAINT [PK_DatosLegales] PRIMARY KEY CLUSTERED 
(
    [IdCliente] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
)

我需要更新IdDatoLegal列。现在我在该表上有80行,所以我需要用数字1,2,3 ... 79,80更新每一行。

我尝试过对存储过程的简单查询,但根本没有成功。

我现在有这个商店程序:

ALTER PROCEDURE dbo.ActualizarDatosLegales
@RowCount int 
AS 
DECLARE @Inicio int
SET @Inicio = 0
WHILE @Inicio < @@RowCount
SET @Inicio += 1;
BEGIN
UPDATE DatosLegales SET IdDatoLegal = @Inicio WHERE (SELECT ROW_NUMBER() OVER (ORDER BY IdCliente) AS RowNum FROM DatosLegales) = @Inicio;
END

我运行时会返回此消息

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

我想这是因为在子查询中(SELECT ROW_NUMBER()OVER(ORDER BY IdCliente)AS RowNum FROM DatosLegales)它返回80行,它应该只返回一行(但每次它应该是一个不同的数字。

您知道我必须添加到子查询中才能使其工作吗?最重要的是,循环和程序的其余部分是正确的吗?

提前致谢

2 个答案:

答案 0 :(得分:18)

您可以使用CTE更新一个语句中的所有行,如下所示。

;WITH T
     AS (SELECT IdDatoLegal,
                Row_number() OVER (ORDER BY IdCliente ) AS RN
         FROM   dbo.DatosLegales)
UPDATE T
SET    IdDatoLegal = RN 

答案 1 :(得分:5)

UPDATE D
SET IdDatoLegal = RN 
FROM DatosLegales D JOIN 
 (
   SELECT IdCliente, Row_number() OVER (ORDER BY IdCliente) AS RN
   FROM   DatosLegales
 ) Temp
ON D.IdCliente = Temp.IdCliente