如何将User和LogIn作为参数传递给存储过程?

时间:2017-05-15 21:54:55

标签: sql-server-2008 tsql stored-procedures sql-server-2012

我有一个脚本会丢弃用户(如果存在),然后重新创建它。我有这样重复30次。如下所示:

IF EXISTS (SELECT 1 FROM sys.sysusers AS s WHERE s.name = N'johndoe')
BEGIN
    PRINT 'Dropping user johndoe...' 
    DROP USER johndoe;
END

CREATE USER [johndoe] FOR LOGIN [uat\johndoe];

我想知道是否可以编写一个接受用户名和域名的存储过程,然后删除并重新创建用户?所以我可以这样打电话:

EXEC usp_DropAndRecreateUsers @username='johndoe', @domainName='uat'

然而,在编写存储过程之后,我意识到它不会像我想象的那么容易。这可能是原因尚未完成的原因。但是,这仍然可以在SQL Server(2008及以上版本)中完成吗?

我所做的是(哪些不起作用):

CREATE PROCEDURE dbo.usp_DropAndRecreateUsers
    (@username varchar(100),
     @domainName varchar(100))
AS 
    DECLARE @loginName varchar(200) = '['+@domainName+'\'+@username+']';

    IF EXISTS (SELECT 1 FROM sys.sysusers AS s WHERE s.name = @username)
    BEGIN
        DROP USER @username;
    END

    CREATE USER @username FOR LOGIN @loginName;

更新: 错误是当我在Drop/Create User @username中使用参数时,它被视为无效的sql语句。错误消息显示为:Incorrect syntax near '@username'.Expecting ID, or QUOTED_ID.

1 个答案:

答案 0 :(得分:1)

而不是从变量运行,创建查询并执行它

CREATE PROCEDURE dbo.USP_DROPANDRECREATEUSERS
    (@username varchar(100),
     @domainName varchar(100))
AS 
    BEGIN
    DECLARE @loginName varchar(200) = '['+@domainName+'\'+@username+']';
    DECLARE @query VARCHAR(MAX);
    IF EXISTS (SELECT 1 FROM sys.sysusers AS s WHERE s.name = @username)
    BEGIN
        SET @query = 'DROP USER ' + @username;
        EXEC (@query);
    END

    SET @query = 'CREATE USER ' + @username + ' FOR LOGIN ' + @loginName;
    EXEC (@query);
    END