这是一个重复的问题: How to use CREATE LOGIN sql statement?
我再次问这个问题是因为我已经尝试过人们在上述问题的答案中提出的建议,并且还尝试了我的Murach SQL Server书籍中的内容,但它没有用。我是否正确运行此脚本,或者无法使用动态SQL创建登录?这是我的代码:
USE MyGuitarShop
IF OBJECT_ID('Admin_For_Login') IS NOT NULL
DROP TABLE Admin_For_Login;
GO
SELECT FirstName, LastName INTO Admin_For_Login FROM Administrators;
DECLARE @FirstName varchar(50), @LastName varchar(50), @NewUser varchar(100), @ExecVar varchar(1000); --variable to replace login name should be a varchar
DECLARE Administrator_Loop_Cursor CURSOR
DYNAMIC
FOR
SELECT FirstName, LastName FROM Admin_For_Login;
OPEN Administrator_Loop_Cursor
FETCH NEXT FROM Administrator_Loop_Cursor INTO @FirstName, @LastName;
--PRINT @FirstName + @LastName;
SELECT @NewUser = @FirstName + @LastName;
--PRINT @NewUser + ' - this is NewUser';
WHILE @@FETCH_STATUS = 0
BEGIN
--FETCH NEXT FROM Administrator_Loop_Cursor INTO @FirstName, @LastName;
IF (@@FETCH_STATUS = 0)
BEGIN
SELECT @NewUser = @FirstName + @LastName;
PRINT @NewUser + ' - this is NewUser';
SET @ExecVar = 'CREATE LOGIN @NewUser WITH PASSWORD = ''temp'' MUST_CHANGE, ';
SET @ExecVar = @ExecVar + 'DEFAULT_DATABASE = MyGuitarShop;';
SET @ExecVar = @ExecVar + ' CREATE USER @NewUser; ';
SET @ExecVar = @ExecVar + 'ALTER ROLE OrderEntry ADD MEMBER @NewUser;';
EXEC (@ExecVar);
FETCH NEXT FROM Administrator_Loop_Cursor INTO @FirstName, @LastName;
END;
IF NOT(@@FETCH_STATUS = 0)
BREAK;
END;
CLOSE Administrator_Loop_Cursor;
DEALLOCATE Administrator_Loop_Cursor;
谢谢!
答案 0 :(得分:1)
更改此部分
SET @ExecVar = 'CREATE LOGIN ' + quotename(@NewUser) + ' WITH PASSWORD = ''temp'' MUST_CHANGE, ';
SET @ExecVar = @ExecVar + 'DEFAULT_DATABASE = MyGuitarShop;';
SET @ExecVar = @ExecVar + ' CREATE USER ' + quotename(@NewUser) + '; ';
SET @ExecVar = @ExecVar + 'ALTER ROLE OrderEntry ADD MEMBER ' + quotename(@NewUser) + ';';
并执行PRINT @ExecVar以在执行之前进行验证