如何正确使用光标?

时间:2015-10-01 15:37:49

标签: sql sql-server

我有一个这样的脚本:

declare @username nvarchar(255)
declare @Alterstatement nvarchar(2000)
declare @userloginname nvarchar(255)
declare @InsertIntoHistory nvarchar(2000)

declare getusername cursor
for 
    select name from [SysAdmin].[dbo].[DisabledAccount]
      where name in (select name from sys.server_principals)

open getusername
Fetch next from getusername into @username

while @@FETCH_STATUS=0
begin 
    set @userloginname = '[' + @username + ']'`

    set @Alterstatement = 'Alter Login' +@userloginname +'Disable'
    set @InsertIntoHistory = 'Insert into DisabledAccountHistory (DisabledName,ServerName) values(''' 
        + @username + ''','''+ @@servername +''')'
    exec(@alterstatement)
    exec(@InsertIntoHistory)
    Fetch next from getusername
    into @username
end

close getusername
deallocate getusername

我使用此脚本禁用某些用户并插入历史记录表。但是当我运行它时,会出现一些问题。例如,当我只有一个我需要禁用的用户时,它将运行3次并在历史表中插入3行。我怎么能问每个用户只运行一次?

1 个答案:

答案 0 :(得分:1)

我会完全摆脱光标,因为这里不需要它。您仍然可以禁用所有登录并将数据插入历史记录表。

declare @SQL nvarchar(max) = ''

select @SQL = @SQL + 'ALTER LOGIN ' + QUOTENAME(name) + ' DISABLE;'
from [SysAdmin].[dbo].[DisabledAccount]
where name in (select name from sys.server_principals)
group by name

exec sp_executesql @SQL

Insert into DisabledAccountHistory 
(
    DisabledName
    , ServerName
) 
select name
    , @@servername 
from [SysAdmin].[dbo].[DisabledAccount]
where name in (select name from sys.server_principals)
group by name