SQL Server TSQL实现用户到数据库的Map

toe95027  于 2022-12-28  发布在  其他
关注(0)|答案(6)|浏览(109)

所以我不能使用企业管理器来做这件事......如果我是的话,我甚至不会问这个问题。所以我想知道是否有一种方法可以通过TSQL来执行一个命令,将用户Map到一个特定的数据库,并授予他们"所有者"权限。
谢谢你...

20jt8wwn

20jt8wwn1#

更改登录的默认数据库:

alter login <loginname> with default_database = <dbname>;

在数据库中为给定登录创建用户:

use <dbname>;
create user <username> from login <loginname>;

使用户成为db_owner组的成员:

use <dbname>
exec sp_addrolemember 'db_owner', '<username>';

创建数据库的登录名“dbo”:

alter authorization on database::<dbname> to <loginname>;
e4eetjau

e4eetjau2#

通常,您希望创建Map到登录名的数据库用户。为此,您将用途:

Create User <username> For LOGIN <loginname>

这显然要求登录名存在,然后调用:

exec sp_addrolemember 'db_owner', <username>

这假定您用来连接到数据库的帐户具有向db_owner角色添加成员的权限。

sz81bmfz

sz81bmfz3#

USE [YourDB]
GO
CREATE USER [xyx] FOR LOGIN [xyz]
GO
ALTER USER [xyz] WITH DEFAULT_SCHEMA=[dbo]
GO
EXEC sp_addrolemember N'db_owner', N'xyz'
GO
djmepvbi

djmepvbi5#

我完整的SQL解决方案。您可以根据需要进行定制:

#region SQL-SERVER-FUNCTION
    /// <summary>
    /// Assign User in to specific role for SQL server database
    /// </summary>
    /// <param name="Server">Server address - example: yourServer.cloudapp.net,1433</param>         
    /// <param name="UserID">User name with sysadmin role</param>
    /// <param name="Database">User database</param>
    /// <param name="Role">New role for this user</param>
    /// <param name="UserToRole">User assigned to new role</param>   
    public static void AddUserToRoles(string Server, string UserID, string Password, string Database, string Role, string UserToRole)
    {               
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = "SERVER = " + Server + "; DATABASE = " + Database + " ; User ID = " + UserID + "; Pwd = " + Password;             
        string sqlCreateDBQuery = " EXEC sp_addrolemember '" + Role + "', " + UserToRole; 
        SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, connection);
        try
        {
            connection.Open();
            myCommand.ExecuteNonQuery();
        }
        catch{}//(System.Exception ex)
        finally
        {
            connection.Close();
        }
        return;
    }

    /// <summary>
    /// Create new User in specified database base on Login in SQL server
    /// </summary>
    /// <param name="Server">Server address - example: yourServer.cloudapp.net,1433</param>         
    /// <param name="UserID">User name with sysadmin role</param>
    /// <param name="Database">Database for created user</param>
    /// <param name="NewUser">New user Name</param>
    /// <param name="FromLogin">Create user base on this SQL server login</param>   
    public static void CreateUserInDatabase(string Server, string UserID, string Password, string Database, string NewUser, string FromLogin)
    {
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = "SERVER = " + Server + "; DATABASE = "+ Database + " ; User ID = " + UserID + "; Pwd = " + Password;
        string sqlCreateDBQuery = "CREATE USER " + NewUser + " FROM LOGIN " + FromLogin;        
        SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, connection);
        try
        {
            connection.Open();
            myCommand.ExecuteNonQuery();
        }
        catch { }//(System.Exception ex)
        finally
        {
            connection.Close();
        }
        return;
    }

    /// <summary>
    /// Create new Login in SQL server
    /// </summary>
    /// <param name="Server">Server address - example: yourServer.cloudapp.net,1433</param>         
    /// <param name="UserID">User name with sysadmin role</param>
    /// <param name="Password">Sysadmin user password</param>
    /// <param name="NewLoginName">New Login Name</param>
    /// <param name="NewLoginPassword">Password for new Login</param>              
    public static void CreateLoginInSqlServer(string Server, string UserID, string Password, string NewLoginName, string NewLoginPassword)
    {
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = "SERVER = " + Server + "; DATABASE = master; User ID = " + UserID + "; Pwd = " + Password;
        string sqlCreateDBQuery = "CREATE LOGIN [" + NewLoginName + "] WITH PASSWORD='"+ NewLoginPassword +"' " +               
            ", CHECK_POLICY=OFF, DEFAULT_DATABASE=db_crs_0002, DEFAULT_LANGUAGE=[English];";         
        SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, connection);
        try
        {
            connection.Open();
            myCommand.ExecuteNonQuery();
        }
        catch { }//(System.Exception ex)
        finally
        {
            connection.Close();
        }
        return;
    }

    /// <summary>
    /// Create new empty database on SQL server base on model database stored in SQL server
    /// </summary>
    /// <param name="Server">Server address - example: yourServer.cloudapp.net,1433</param>
    /// <param name="NewDatabaseName">Name for new database</param>
    /// <param name="UserID">User name with sysadmin role</param>
    /// <param name="Password">Sysadmin user password</param>
    public static void CreateNewDatabaseSqlserver(string Server, string NewDatabaseName, string UserID, string Password)                 
    {
        string sqlCreateDBQuery = " CREATE DATABASE " + NewDatabaseName;
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = "SERVER = " + Server + "; DATABASE = master; User ID = " + UserID + "; Pwd = " + Password;  
        SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, connection);
        try
        {
            connection.Open();
            myCommand.ExecuteNonQuery();  
        }
        catch { }//(System.Exception ex)
        finally
        {
            connection.Close();
        }
        return;
    }
    #endregion

使用:在SQL Server上创建具有sysadmin权限的登录名:管理API

SQLserverAPI.CreateNewDatabaseSqlserver("yourServer.cloudapp.net,1433", "databaseName", "AdminAPI", "password*");
        SQLserverAPI.CreateLoginInSqlServer("yourServer.cloudapp.net,1433", "AdminAPI", "password*", "My_Login", "password*");
        SQLserverAPI.CreateUserInDatabase("yourServer.cloudapp.net,1433", "AdminAPI", "password*", "databaseName", "User1", "My_Login");
        SQLserverAPI.AddUserToRoles("yourServer.cloudapp.net,1433", "AdminAPI", "password*", "databaseName", "db_datareader", "User1");
        SQLserverAPI.AddUserToRoles("yourServer.cloudapp.net,1433", "AdminAPI", "password*", "databaseName", "db_datawriter", "User1");
        SQLserverAPI.AddUserToRoles("yourServer.cloudapp.net,1433", "AdminAPI", "password*", "databaseName", "db_owner", "User1");
kkih6yb8

kkih6yb86#

当然,通常情况下,您不希望将所有者权限授予用户,这就是我们DBA世界中的人所说的“一件坏事”。

相关问题