SQL Server:遍历每一行,将增加的值添加到列

时间:2016-01-20 08:59:38

标签: sql sql-server tsql

我刚刚向Person_Id_Helper添加了一个新列MyTable。它应该按照表格现在排序的顺序包含1,2,3等。

这就是我想要做的事情:

DECLARE @i INT = 1, @NumberOfRows INT = SELECT COUNT(*) FROM MyTable 

WHILE(@i <= @NumberOfRows)
BEGIN
   -- Person_Id_Helper = @i
   -- @i = @i + 1       
END

我该怎么写?

4 个答案:

答案 0 :(得分:4)

我认为,在列中保持排序可能是错误的想法。但是 - 当然! - 在while循环中执行此操作是错误的想法。

了解基于行和基于集合的方法。 SQL需要基于集合的思考......

以此为例说明如何执行此操作(只需将其粘贴到空的查询窗口并执行,以适应您的需求):

DECLARE @tbl TABLE(SortDate DATE, Inx INT);
INSERT INTO @tbl VALUES({d'2016-01-20'},0)
                      ,({d'2016-01-19'},0)
                      ,({d'2016-01-14'},0)
                      ,({d'2016-01-16'},0);
WITH cte AS
(
       SELECT Inx,ROW_NUMBER() OVER(ORDER BY SortDate) AS RN
       FROM @tbl
)
UPDATE cte SET Inx=RN;

SELECT * FROM @tbl;

答案 1 :(得分:2)

我认为这是你想要达到的目标 -

DECLARE @i INT = 0
UPDATE MyTable
SET 
   @i = Person_Id_Helper = @i + 1

现在检查您的列值。

我们不能在update语句中使用ORDER BY子句。但是在这里使用它是更新的查询。

UPDATE t
SET Person_Id_Helper = rn.RowNum
FROM MyTable t
INNER JOIN (SELECT
        ID
        ,ROW_NUMBER() OVER (ORDER BY ID) AS RowNum
    FROM MyTable) rn
    ON t.ID = rn.ID

@shungo:谢谢你指出。

答案 2 :(得分:0)

试试这个,

DECLARE @tbl TABLE
  (
     datecolumn DATE,
     Person_Id_Helper  INT
  );

INSERT INTO @tbl
VALUES     ({d'2016-01-20'},
            0),
            ({d'2016-01-19'},
             0),
            ({d'2016-01-14'},
             0),
            ({d'2016-01-16'},
             0);

SELECT *
FROM   @tbl;

UPDATE T
SET    Person_Id_Helper = rn
FROM   (SELECT Person_Id_Helper,
               Row_number()
                 OVER(
                   ORDER BY datecolumn) AS rn
        FROM   @tbl) T

SELECT *
FROM   @tbl;

答案 3 :(得分:0)

enter image description here循环使用sqlserver

中的游标添加值
 CREATE TABLE [dbo].[Table1](
    [PID] [int] NULL,
    [ProductDesc] [nvarchar](50) NULL,
    [ProductCode] [nvarchar](10) NULL
) ON [PRIMARY]


GO
INSERT [dbo].[Table1] ([PID], [ProductDesc], [ProductCode], [Person_Id_Helper]) VALUES (1, N'Packet-Eye', N'P001', NULL)
GO
INSERT [dbo].[Table1] ([PID], [ProductDesc], [ProductCode], [Person_Id_Helper]) VALUES (2, N'Wiggy', N'W099 ', NULL)
GO
INSERT [dbo].[Table1] ([PID], [ProductDesc], [ProductCode], [Person_Id_Helper]) VALUES (3, N'Wimax-Lite', N'W001', NULL)
GO
INSERT [dbo].[Table1] ([PID], [ProductDesc], [ProductCode], [Person_Id_Helper]) VALUES (4, N'Wimax-Home', N'e W002 ', NULL)
GO

Declare @count int
DECLARE @PID int 
set @count=0
DECLARE c1 CURSOR READ_ONLY
FOR 
SELECT [PID] FROM [Table1] 
OPEN c1 
FETCH NEXT FROM c1 INTO @PID 
WHILE @@FETCH_STATUS = 0 
BEGIN 
set @count=@count+1
update Table1 set Person_Id_Helper=@count where [PID]=@PID
FETCH NEXT FROM c1 INTO @PID END 
CLOSE c1 
DEALLOCATE c1

select * from Table1