How to get default database name using Transact-SQL query? - sql-server

My initial concern was to DROP DATABASE MyDB when a certain condition is met but I get this error:
Database 'MyDB' is still in use
So, the answer I found was to do
USE master
DROP DATABASE MyDB
It works, but for my case there is no guarantee whether master will be the default database on the server or not.
I would like to know how do I get the default database name for that particular server so that I can write something like
USE Default_DB
DROP DATABASE MyDB

The default database is set per login, not for the server. If not specified when creating a login, it defaults to 'master'.
You change it like this:
ALTER LOGIN [user_name] WITH DEFAULT_DATABASE = [default_database]
Ref: CREATE LOGIN
To answer your actual question, you should always move to 'master' to delete a database:
USE master
GO
DROP DATABASE MyDB
GO

Related

How to get Database Name in a Logon SQL Trigger

How to get Database Name in a Logon Trigger
tried several tsql code
CREATE TRIGGER tr_stop_excel_users
ON ALL SERVER FOR LOGON
AS
BEGIN
IF (SELECT DB_NAME() FROM sys.databases) = 'TESTDB' and ORIGINAL_LOGIN() <> N'xx\xxxxxxx' AND APP_NAME() LIKE '%Microsoft Office%' OR APP_NAME() LIKE '%EXCEL%' OR APP_NAME() LIKE '%ACCESS%
ROLLBACK;
END
above the DB_NAME always yields master
I am trying to get Database Name in a Logon Trigger and its not working in any way I try….below the DB_NAME is always master…what I am trying to do here is to block users who are using excel to query the TESTDB database….
If you are using Db_Name in LOGON trigger, you will get the default database name. So as you get the master, it shows that login's default database is master.
If you need to get other names, you need to change your connection string in application, or provide database name in SSMS Login prompt screen, or any other places where you can provide the database name(Go to Options/Connection Properties/Connect to Database in Login prompt screen in SSMS)
If you do not provide database name, login will connect to its default database, that is set in Security/Login/Default Database
Solution for you
Using Db_Name is not a good option for you, I recommend you to use APP_NAME function instead.
Same problem discussed in StackExchange: https://dba.stackexchange.com/questions/40155/prevent-users-from-using-power-pivot-excel-connections-to-a-database

Azure SQL database is not designed to allow users change their passwords. Any workaround?

We start with the facts:
Logins are in the master database,
users are in a user database.
Azure does not allow to change database with USE statement.
SQL requires the user to be in the master database in order to execute ALTER LOGIN statement.
.
--USE master;
--**ERROR** USE statement is not supported to switch between databases. Use a new connection to connect to a different database.
--GO
ALTER LOGIN nonadmin WITH PASSWORD='new5as$word' OLD_PASSWORD='old5a$sword';
--**ERROR** User must be in the master database.
GO
It is possible to migrate the database to contained mode, but this way would be quite exhausting as the legacy code have plenty of places like this:
IF(OBJECT_ID('tempdb..#temp1') IS NOT NULL)
BEGIN
DROP TABLE #temp1
END;
CREATE TABLE #temp1
(
id int not null IDENTITY,
CONSTRAINT PK_tt1 PRIMARY KEY(id)
)
Is there a suitable workaround except migrating to contained database mode?
You are trying to change the password of a contained user. Contained users don't have server logins so you can't use the ALTER LOGIN statement.
You need to use ALTER USER :
ALTER USER nonadmin WITH PASSWORD='new5as$word' OLD_PASSWORD='old5a$sword';
A server login is the identity with which you login to a server. In SSMS, you'll find logins in a server's Security node. These logins are then granted access to specific databases as users. These users are stored in the master database.
elect the Database choice on the left, then select Servers:
Then, after selecting the server of choice, you'll see the option on the right for resetting admin password:
source : Password reset for Azure database

SQL Server - Create a new database for a user and ONLY give them access / view rights to that one DB

I have admin rights on a SQL Server 2012 Server and have a user that wants me to create a "throw away" database for them on the server.
Basically, I'm looking to:
Create this database
Give the user full access / rights TO ONLY THAT DATABASE
Have them see it and its schema - but not any other DBs - in the SSMS Object Explorer
I've found quite a few answers around online and the one that got me closest was this one:
https://stackoverflow.com/a/15400392/1693085
Basically giving me these lines of SQL to execute:
--Step 1: (create a new user)
create LOGIN hello WITH PASSWORD='foo', CHECK_POLICY = OFF;
-- Step 2:(deny view to any database)
USE master;
GO
DENY VIEW ANY DATABASE TO hello;
-- step 3 (then authorized the user for that specific database , you have to use the master by doing use master as below)
USE master;
GO
ALTER AUTHORIZATION ON DATABASE::yourDB TO hello;
GO
However, when I then log in as this user and right click on a created table, I get the following error repeated dozens of times:
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
------------------------------
ADDITIONAL INFORMATION:
The EXECUTE permission was denied on the object 'xp_instance_regread', database 'mssqlsystemresource', schema 'sys'.
And, if I ignore it and try and delete the table anyways, I get basically the same error again.
All I basically want to do is create a user and ensure they have no more access than that one database, but have full access on that one...
Am I doing something wrong / What should I change??
Thanks!!!
You can get around this by granting the user permission to the stored procedure:
USE master
GO
GRANT EXEC ON OBJECT::master.dbo.xp_instance_regread TO hello
GO

Login User Mapping issue in SQL Server 2008

A while back I set up a database under SQL Server 2008 called myDB in Windows XP, then under Logins under the server, I clicked Properties on my computer login name COMP23/Andrew and mapped myDB database to this using dbowner as its rights.
Then I cloned this XP installation as a backup, installed Visa, realising I did not want Vista I re-imaged back my original XP copy onto the same machine. However the DB mapping has got really confused! Basically under the server login COMP23\Andrew, it says its mapped to myDB, but when I click myDB and look at its users its not there. I think its lost its SID mapping because it thinks its a new machine.
Under the server login COMP23\Andrew I can't untick the mapping to myDB as when I do it says "Cannot drop the user dbo". I can't alter the dbo user either - it won't let me. But nor can I make the user appear under myDB users! Which means I can't login through my website settings (asp.net web.config) file! When I login it just says Cannot open database "myDB" requested by the login. The login failed.
Login failed for user 'COMP23\ASPNET'
Any ideas? How I can remap this properly? I've even tried reinstalling SQL Server 2008 but the computer name is still there mapped to the database.
Because dbo is the owner of the database, its mapping must be changed by changing the owner of the database:
ALTER AUTHORIZATION ON database::[<yourdb>] TO [sa];
First of all, you can't have quote marks surrounding the stored procedure name. Secondly, it isn't autofix but auto_fix.
Finally, once those corrections are made, you get this error message:
Msg 15600, Level 15, State 1, Procedure sp_change_users_login, Line
181 An invalid parameter or option was specified for procedure
'sys.sp_change_users_login'.
when you run this command:
EXEC sp_change_users_login #Action = 'auto_fix', #LoginName = '<your username>'
Since you mentioned the SID mapping issue, have you tried using sp_change_users_login? Use the autofix option to re-map your login to the one in the database.
For your example above you should execute the following while connected to the database
EXEC `sp_change_users_login` #Action = 'autofix', #LoginName = 'COMP23\ASPNET'
USE [Database]
GO
ALTER USER [dbo] WITH NAME=[username]
GO
sp_changedbowner 'sa'
GO

How to change default database in SQL Server without using MS SQL Server Management Studio?

I dropped a database from SQL Server, however it turns out that my login was set to use the dropped database as its default. I can connect to SQL Server Management Studio by using the 'options' button in the connection dialog and selecting 'master' as the database to connect to. However, whenever I try to do anything in object explorer, it tries to connect using my default database and fails.
Does anyone know how to set my default database without using object explorer?
What you can do is set your default database using the sp_defaultdb system stored procedure. Log in as you have done and then click the New Query button. After that simply run the sp_defaultdb command as follows:
Exec sp_defaultdb #loginame='login', #defdb='master'
Alternative to sp_defaultdb (which will be removed in a future version of Microsoft SQL Server) could be ALTER LOGIN:
ALTER LOGIN [my_user_name] WITH DEFAULT_DATABASE = [new_default_database]
Note: user and database names are provided without quotes (unlike the sp_defaultdb solution). Brackets are needed if name had special chars (most common example will be domain user which is domain\username and won't work without brackets):
ALTER LOGIN me WITH DEFAULT_DATABASE = my_database
but
ALTER LOGIN [EVILCORP\j.smith28] WITH DEFAULT_DATABASE = [prod\v-45]
To do it the GUI way, you need to go edit your login. One of its properties is the default database used for that login. You can find the list of logins under the Logins node under the Security node. Then select your login and right-click and pick Properties. Change the default database and your life will be better!
Note that someone with sysadmin privs needs to be able to login to do this or to run the query from the previous post.
Thanks to this post, I found an easier answer:
Open Sql Server Management Studio
Go to object Explorer -> Security -> Logins
Right click on the login and select properties
And in the properties window change the default database and click OK.
If you don't have permissions to change your default DB you could manually select a different DB at the top of your queries...
USE [SomeOtherDb]
SELECT 'I am now using a different DB'
Will work as long as you have permission to the other DB
Click on Change Connection icon
Click Options<<
Select the db from Connect to database drop down
Click on options on the connect to Server dialog and on the Connection Properties, you can choose the database to connect to on startup. Its better to leave it default which will make master as default. Otherwise you might inadvertently run sql on a wrong database after connecting to a database.
I'll also prefer ALTER LOGIN Command as in accepted answer and described here
But for GUI lover
Go to [SERVER INSTANCE] --> Security --> Logins --> [YOUR LOGIN]
Right Click on [YOUR LOGIN]
Update the Default Database Option at the bottom of the page
Tired of reading!!! just look at following
In case you can't login to SQL Server:
sqlcmd –E -S InstanceName –d master
Reference:
https://support.microsoft.com/en-us/kb/307864
This may or may not exactly answer the question, but I ran into this issue (and question) when I had changed my account to have a new database I had created as my "default database". Then I deleted that database and wanted to test my creation script, from scratch. I logged off SSMS and was going to go back in, but was denied -- cannot log into default database was the error. D'oh!
What I did was, on the login dialog for SSMS, go to Options, Connection Properties, then type master on the "Connect to database" combobox. Click Connect. Got me in. From there you can run the command to:
ALTER LOGIN [DOMAIN\useracct] WITH DEFAULT_DATABASE=[master]
GO
There is a little icon for change the connection, click on that and then go to Options and Select the db from Connect to database drop down
With the MSSQL queries below, you can change database on sqlcmd:
USE testdb
GO
Then, you can check the currently used database:
SELECT DB_NAME()
GO
testdb
Then, you can show all the existed databases:
SELECT name FROM master.sys.databases
GO
master
tempdb
model
msdb
testdb
In addition, if you don't specify a database on sqlcmd, "master" database is used by default.
If you use windows authentication, and you don't know a password to login as a user via username and password, you can do this: on the login-screen on SSMS click options at the bottom right, then go to the connection properties tab. Then you can type in manually the name of another database you have access to, over where it says , which will let you connect. Then follow the other advice for changing your default database
https://gyazo.com/c3d04c600311c08cb685bb668b569a67

Resources