6

我现在有这张桌子

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 行,它应该只返回一个(但每次它应该是一个不同的数字。

你知道我必须向子查询添加什么才能使其工作吗?最重要的是,循环和其余程序是否正确?

提前致谢

4

2 回答 2

18

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

;WITH T
     AS (SELECT IdDatoLegal,
                Row_number() OVER (ORDER BY IdCliente ) AS RN
         FROM   dbo.DatosLegales)
UPDATE T
SET    IdDatoLegal = RN 
于 2012-12-14T18:09:16.880 回答
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
于 2012-12-14T18:14:02.230 回答