How to create new SQL Server 2012 login without SQL Server Management Studio? - sql

I have creating my system using Entity Framework code first for it create database automatic if it is not exist, but first, I need a user for access database
But I know only create user of SQL Server with SQL Server Management Studio, but I'm in a situation, where computer have SQL Server 2012 installed, but have not SQL Server Management Studio
What can I do for create a new database user without SQL Server Management Studio? Or have any solution with Entity Framework like it create database automatic?

To create a login from windows domain account using SQL Server Windows Authentication
CREATE LOGIN [Domain\Windows_UserName] FROM WINDOWS;
GO
Then you have to Create A user with that Login
CREATE USER [Domain\Windows_UserName] FOR LOGIN [Domain\Windows_UserName];
GO
For Sql Server Authentication
CREATE LOGIN Login_Name WITH PASSWORD = 'ksblaksvfdh&';
GO

You can use SQL Server SMO to programatically create the database Users and add it the 1st time in your EF Code First DatabaseInitializer. Use with caution though ;)
Add References to the following.
Microsoft.SqlServer.ConnectionInfo
Microsoft.SqlServer.Smo
Microsoft.SqlServer.SqlEnum
Then create an SQL login and also add the user to your target database
var serverName = "."; // Your SQL Server Instance name
var databaseName = "Test"; // Your database name
var loginName = "testuserY"; // Your login name (should not exist - or you should add code to check if the login exists)
Server svr = new Server(serverName);
var db = svr.Databases[databaseName];
if (db != null)
{
// You probably want to create a login and add as a user to your database
Login login = new Login(svr, loginName);
login.DefaultDatabase = "master"; // Logins typically have master as default database
login.LoginType = LoginType.SqlLogin;
login.Create("foobar", LoginCreateOptions.None); // Enter a suitable password
login.Enable();
User user = new User(db, loginName);
user.UserType = UserType.SqlLogin;
user.Login = login.Name;
user.Create();
// add a role
user.AddToRole("db_owner");
}
Source of Source Code: https://stackoverflow.com/a/7899436/325521

Related

Azure Elastic Job Agent - Credentials

I want to refresh my tables in the same database with my queries using with Elastic Job Agent. I need to create credential first to connect database. How can I arrange the credentials in this case? Every documentation they have either 2 database or 2 server.
I found 2 sources but I couldn't understand the concept. Can you please explain it to me in a clear way?
Source 1 : Microsoft document
--Connect to the new job database specified when creating the Elastic Job agent
-- Create a database master key if one does not already exist, using your own password.
CREATE MASTER KEY ENCRYPTION BY PASSWORD='<EnterStrongPasswordHere>';
-- Create two database scoped credentials.
-- The credential to connect to the Azure SQL logical server, to execute jobs
CREATE DATABASE SCOPED CREDENTIAL job_credential WITH IDENTITY = 'job_credential',
SECRET = '<EnterStrongPasswordHere>';
GO
-- The credential to connect to the Azure SQL logical server, to refresh the database metadata in server
CREATE DATABASE SCOPED CREDENTIAL refresh_credential WITH IDENTITY = 'refresh_credential',
SECRET = '<EnterStrongPasswordHere>';
GO
Source 2: link
--In the master database
CREATE LOGIN mastercredential WITH PASSWORD='YourPassword1';
CREATE LOGIN jobcredential WITH PASSWORD='YourPassword2';
CREATE USER mastercredential FROM LOGIN mastercredential;
--In the job database
CREATE USER mastercredential FROM LOGIN mastercredential;
--In the target database
CREATE USER jobcredential FROM LOGIN jobcredential;
-- In the job database
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'YourPassword3';
CREATE DATABASE SCOPED CREDENTIAL mastercredential
WITH IDENTITY = 'mastercredential',
SECRET = 'YourPassword1';
CREATE DATABASE SCOPED CREDENTIAL jobcredential
WITH IDENTITY = 'jobcredential',
SECRET = 'YourPassword2';

How to create a contained database and user in azure sql

I am trying to create a contained user for just one database in Azure SQL Server,
I have tried using the sp_configure keyword, it says it is not available in the version of the SQL Server I am using.
Also, I used the Alter database statement, I got the error below:
ALTER DATABASE statement failed; this functionality is not available
in the current edition of SQL Server.
Please, how can I solve this problem???
You do not need to run the ALTER DATABASE ... SET CONTAINMENT command on Azure SQL DBs to accept contained users - it is already enabled by default. You simply need to create the user with just a login and password. A simple example of a contained user with password:
CREATE USER yourUser WITH PASSWORD = 'yourPassword';
See the official documentation for more examples:
https://learn.microsoft.com/en-us/sql/t-sql/statements/create-user-transact-sql?view=sql-server-ver15#e-creating-a-contained-database-user-with-password
https://learn.microsoft.com/en-us/sql/t-sql/statements/create-user-transact-sql?view=sql-server-ver15#f-creating-a-contained-database-user-for-a-domain-login
sp_configure is not supported in Azure SQL database, even use the Alter database:
In Azure SQL database, login is used to login the Azure SQL server, user is to connect to the database. User is database level, and login is server level.
Create login in master DB(( Login must be created in master DB)):
CREATE LOGIN AbolrousHazem
WITH PASSWORD = '340$Uuxwp7Mcxo7Khy';
Then we can create user in user DB( create the database contained user in user DB):
CREATE USER AbolrousHazem FOR LOGIN AbolrousHazem;
GO
For more details, please ref: https://learn.microsoft.com/en-us/azure/azure-sql/database/logins-create-manage

Getting last updated on a table as a dbowner

I need to get a last updated timestamp when for a table. This operation is to be performed by a dbowner, who has GRANT EXEC permissions on all sprocs. Any ideas how to accomplish this? Here is what I tried.
I tried getting this info using SMO, but because of the lack of permissions it returns a null table object.
using (SqlConnection connection = new SqlConnection(connectionString))
{
ServerConnection serverConnection = new ServerConnection(connection);
Server server = new Server(serverConnection);
Database database = server.Databases["MyDb"];
Table table = database.Tables["MyTable"]; // here table is null for dbowner user, but a valid object for a super user
DateTime lastModified = table.DateLastModified;
}
Also tried creating a new sproc, but when I call it I get The user does not have permission to perform this action.
CREATE PROCEDURE getTableLastModifiedDate
(
#TableName nvarchar(max)
)
AS
BEGIN
SELECT last_user_update FROM sys.dm_db_index_usage_stats
WHERE OBJECT_NAME(OBJECT_ID)=#TableName AND database_id = DB_ID(DB_NAME())
END
GO
From the help topic for sys.dm_db_index_usage_stats:
Requires VIEW SERVER STATE permission.
If you look at the server permissions: VIEW SERVER STATE is implied by ALTER SERVER STATE in turn implied by CONTROL SERVER. System administrators have the required permissions, database administrators do not.
The best solution is to sign the procedure and then grant the required permission through the signature, see Signing an activated procedure for an example.

query to change database user in sql server 2008

I am using SQL Server authentication with login name sa (default)
When I execute query
select session_user
I get dbo as a user. I want to change this, how can I do this using SQL query? Also what is a schema in SQL?
Sql server has 2 different notions
login: what you use to connect to the server
User: what you give rights to in a database
When your login is granted database access you are actually creating a database user mapped to the login. The sa is the system administrator account and mapped to the dbo (database owner user) on the system databases. When you are logged in with a user with the create database right and create a new database this login will be automatically mapped to the dbo user.
If you want to change this afterwards, you need to map the dbo user to a new login. Afterwards you can map the sa account to another database user.
use master
create login xxx with password = 'yyy', check_policy = off
use <yourdatabase>
exec sp_changedbowner 'xxx'
create user 'newuser' from login 'sa'
This way the sa login will be mapped to the newuser database user from now on.
A schema is a securable item which can be used to group database objects. Each database user has a "default schema" assigned.
Schema is a way of categorising the objects in a database. It can be useful if you have several applications share a single database and while there is some common set of data that all application accesses.
DBO is a DataBase Owner. You have created the database and you are a database owner.

How to connect an existing SQL Server login to an existing SQL Server database user of same name

Is there a SQL Server command to connect a user of a single database to a login for the database server of the same name?
For example:
Database Server - Default Instance
Database: TestDB
Server Login - TestUser
Existing user on TestDB - TestUser
If I try to make the TestUser login a user of the TestDB database, the "User, group, or role" already exists.
Does anybody know of an easy way to assign the DB user to the server login?
The new way (SQL 2008 onwards) is to use ALTER USER
ALTER USER OrphanUser WITH LOGIN = correctedLoginName;
I think it's sp_change_users_login. It's been a little while, but I used to do that when detaching and reattaching databases.
I've used the sp_change_users_login procedure to accomplish, I think, that scenario.