我有一个简单的查询:
select distinct USERS from [USER_TABLE]
返回类似
的内容Thunder Cat
He Man
我想要的是迭代这个列表并将其插入另一个表中:
User 1: Thunder Cat
User 2: He Man
我正在尝试这样的apporo:
declare @i int = 1;
while (select distinct [USER] from [USER_TABLE]) > 0
begin
exec dbo.audit_log concat('User ', @i), 'test';
end
(其中audit_log是将行插入日志表的存储过程)
然而,这给了我一个错误:Incorrect syntax near 'User '.
答案 0 :(得分:2)
您需要遍历数据集。试试这个:
DECLARE @Table TABLE
(
[Row_Num] INT IDENTITY(1,1),
[Users] VARCHAR(100)
);
INSERT INTO @Table
SELECT DISTINCT [USERS]
FROM [User_Table]
DECLARE @loopCounter INT = 1,
@LastRowNum INT = (SELECT COUNT(*) FROM @Table),
@user VARCHAR(100);
WHILE (@loopCounter <= @LastRowNum)
BEGIN
SET @user = (SELECT [Users] FROM @Table WHERE Row_Num = @loopCounter);
EXEC dbo.audit_log @user,' test';
SET @loopCounter = @loopCounter + 1;
END