SQL中迁移sql用户及密码脚本
编写人:CC阿爸
2014-6-20
在日常SQL数据库的操作中,常常需要迁移数据库或重装服务器,这时候,一些之前建立的login账户,必须重新建立,以下可以通过脚本,将其导出,在重装或移植时,可方便能过执行脚本来生成,不用再手动一个个建立。大大提高操作效率。
select ‘create login [‘ + p.name + ‘] ‘ +
case when p.type in(‘U‘,‘G‘) then ‘from windows ‘ else ‘‘ end +‘with ‘ +
case when p.type = ‘S‘ then ‘password = ‘ + master.sys.fn_varbintohexstr(l.password_hash) +
‘ hashed, ‘ + ‘sid = ‘ + master.sys.fn_varbintohexstr(l.sid) + ‘, check_expiration = ‘ +
case when l.is_expiration_checked > 0 then ‘ON, ‘ else ‘OFF, ‘ end + ‘check_policy = ‘ +
case when l.is_policy_checked > 0 then ‘ON, ‘ else ‘OFF, ‘ end +
case when l.credential_id > 0 then ‘credential = ‘ + c.name + ‘, ‘ else ‘‘ end
else ‘‘
end +
‘default_database = ‘ + p.default_database_name +
case when len(p.default_language_name) > 0
then ‘, default_language = ‘ + p.default_language_name else ‘‘ end
from sys.server_principals p
left join sys.sql_logins l on p.principal_id = l.principal_id
left join sys.credentials c on l.credential_id = c.credential_id
where p.type in(‘S‘,‘U‘,‘G‘) and p.name <> ‘sa‘