简体   繁体   English

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

[英]How to update a column via Row_Number with a different value for each row?

I have this table right now 我现在有这张桌子

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]
)

I need to update the IdDatoLegal Column. 我需要更新IdDatoLegal列。 Right now I have 80 rows on that table, so I need to update each row with the numbers 1, 2, 3... 79, 80. 现在我在该表上有80行,所以我需要用数字1,2,3 ... 79,80更新每一行。

I have tried simple queries to stored procedures with no succeed at all. 我已经尝试过对存储过程的简单查询,但根本没有成功。

I have this stores procedure right now: 我现在有这个商店程序:

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

It returns this message when I run it 它在运行时返回此消息

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

I guess that's because in the subquery (SELECT ROW_NUMBER() OVER (ORDER BY IdCliente) AS RowNum FROM DatosLegales) it returns 80 rows where it should only return one (but each time it should be a diferent number. 我想这是因为在子查询(SELECT ROW_NUMBER()OVER(ORDER BY IdCliente)AS RowNum FROM DatosLegales)中它返回80行,它应该只返回一行(但每次它应该是一个不同的数字。

Do you know what do I have to add to the subquery to make it work? 你知道我必须添加到子查询以使其工作吗? and above all, Is the loop and the rest of the procedure right? 最重要的是,循环和程序的其余部分是正确的吗?

thanks in advance 提前致谢

You can update all the rows in one statement using a CTE as below. 您可以使用CTE更新一个语句中的所有行,如下所示。

;WITH T
     AS (SELECT IdDatoLegal,
                Row_number() OVER (ORDER BY IdCliente ) AS RN
         FROM   dbo.DatosLegales)
UPDATE T
SET    IdDatoLegal = RN 
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM