我想要完成的是删除任何额外的用户/模式(我想要保留的NOT IN中列出的任何内容)。我不能删除用户,以防他们以相同的名称附加到任何模式(有些是这样的,有些不是),所以我试图检查我想删除的模式是否存在,如果是的话,我想删除它。我想对使用相同逻辑连接到数据库的任何用户执行相同的操作。
我的问题是,当我运行脚本时,它会找到我想要删除的用户/模式,但是会抛出错误,上面写着“无效的列名'USERNAME HERE'。
有什么想法吗?
declare @sql nvarchar(max)
set @sql = ''
SELECT @sql = @sql+
'
IF EXISTS (SELECT NAME FROM sys.schemas WHERE NAME = "'+ name +'" )
BEGIN
DROP SCHEMA "'+ name +'"
END
IF EXISTS (SELECT NAME FROM dbo.sysusers WHERE NAME = "'+ name +'" )
BEGIN
DROP USER "'+ name +'"
END
'
FROM
dbo.sysusers
WHERE
name NOT IN('dbo','guest','INFORMATION_SCHEMA','sys','public')
AND LEFT(name,3) <> 'db_'
order by
name
execute ( @sql )
--print (@sql)
答案 0 :(得分:1)
对于任何好奇的人我都使用游标工作。
DECLARE @UserName varchar(256)
DECLARE @sqlSchema varchar(100)
DECLARE @sqlUser varchar(100)
DECLARE csrUser CURSOR FOR
SELECT [name] FROM sys.database_principals WHERE name
NOT IN('dbo','guest','INFORMATION_SCHEMA','sys','public') AND LEFT(name,3) <> 'db_'
ORDER BY [name]
OPEN csrUser
FETCH NEXT FROM csrUser INTO @UserName
WHILE @@FETCH_STATUS <> -1
BEGIN
IF EXISTS(SELECT NAME FROM sys.schemas WHERE NAME = @userName )
BEGIN
set @sqlSchema = 'drop schema "' + @userName + '"'
print @sqlSchema
--exec (@sqlSchema)
WAITFOR DELAY '00:00:05'
END
set @sqlUser = 'drop user "' + @userName + '"'
print @sqlUser
--exec (@sqlUser)
FETCH NEXT FROM csrUser INTO @UserName
END
CLOSE csrUser
DEALLOCATE csrUser
我必须包含WAITFOR DELAY,因为每当它试图删除用户时,SQL仍然说它与模式相关联。
答案 1 :(得分:0)
您是否使用"
(双引号)或''
(两个单引号)来转义引号?看起来你使用的是不正确的双引号。
它应该是:
declare @sql nvarchar(max)
set @sql = ''
SELECT @sql = @sql+
'
IF EXISTS (SELECT NAME FROM sys.schemas WHERE NAME = '''+ name +''' )
BEGIN
DROP SCHEMA '''+ name +'''
END
IF EXISTS (SELECT NAME FROM dbo.sysusers WHERE NAME = '''+ name +''' )
BEGIN
DROP USER '''+ name +'''
END
'
FROM
dbo.sysusers
WHERE
name NOT IN('dbo','guest','INFORMATION_SCHEMA','sys','public')
AND LEFT(name,3) <> 'db_'
order by
name
--execute ( @sql )
print (@sql)