manipulate array of data in SQL

来源:互联网 发布:淘宝客如何转成淘口令 编辑:程序博客网 时间:2024/04/30 05:42

As we know, SQL server lacks of concept of array. 

a workaround is to store the data in a table variable and then iterate it.

one way to do iterate is using cursor, but it's slow

another way is add a id column in the table variable, and then access the record in table variable with index.





DECLARE @UserName VARCHAR(30), @DisplayName VARCHAR(30)


DECLARE @Users TABLE(Id int identity(1,1), UserName VARCHAR(30), DisplayName VARCHAR(30))
INSERT INTO @Users
VALUES
('lxing', 'Lili')
,('ashan', 'Allen')


DECLARE @RowsToProcess  int = @@ROWCOUNT
DECLARE @Row INT=1




WHILE(@Row <= @RowsToProcess)


BEGIN


SELECT @UserName = UserName, @DisplayName = DisplayName FROM @Users where Id = @Row


declare @uid int


--insert user


SET @Row = @Row + 1
END

0 0