How to get Database Name in a Logon SQL Trigger - sql-server

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

Related

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

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

Unable to delete the database user as the user is already logged in currently. error 15434

I have created the user sagar in SQL Server 2012 database and mapped it to the XYZ database. After some time I deleted the XYZ database and now I don't need the existing user sagar also. But when I try to delete the user from SQL Srever Management Studio. I am getting the following exception
Could not drop login 'sagar' as the user is currently logged in. error:15434
User can be deleted after killing the session by identifying the session_id of the user.
SELECT session_id
FROM sys.dm_exec_sessions
WHERE login_name = 'sagar'
KILL 51 --51 is session_id here, you may get different id
Now you can delete the login simply by executing the below query (or) by using sql server management studio options.
DROP LOGIN 'sagar'
How to delete yourself as a Login. E.g. You may want to do this when the hostname changed so that Sql Server records your Login under the old hosthame.
Login to SSMS. Select the 'sa' account and change the password to something you will remember.
Close down SSMS, start it up again but login as 'sa' this time. Select the Login you wish to delete, right click for Delete.
You will probably be told that Login owns one or more databases.
Login 'hostname\The Login' owns one or more database(s).
Change the owner of the databases before dropping the logon. [MS Sql Server Error 15174]
To list the owner of every database:
select suser_sname(owner_sid) from sys.databases
To change the owner of every database to 'sa'
EXEC sp_MSforeachdb 'EXEC [?]..sp_changedbowner ''sa'' '
<-- This sp_MSforeachdb will probably fail for one or two, as it did for me. In my case because that database was single user. Changing the rogue database to multi-user fixed that. Then I just ran EXEC sp_MSforeachdb ... again.
To check, run
select suser_sname(owner_sid) from sys.databases
again to ensure the Login is gone
Now delete that login.

Where to set permissions to all server for logon trigger on sql server 2005

I need to keep track of the last login time for each user in our SQL Server 2005 database.
I created a trigger like this:
CREATE TRIGGER LogonTimeStamp
ON ALL SERVER FOR LOGON
AS
BEGIN
IF EXISTS (SELECT * FROM miscdb..user_last_login WHERE user_id = SYSTEM_USER)
UPDATE miscdb..user_last_login SET last_login = GETDATE() WHERE user_id = SYSTEM_USER
ELSE
INSERT INTO miscdb..user_last_login (user_id,last_login) VALUES (SYSTEM_USER,GETDATE())
END;
go
This trigger works for users that are system admins but it won't allow regular users to login. I have granted public select,insert and update to the table but that doesn't seem to be the issue. Is there a way to set permissions on the trigger? Is there something else I am missing?
Regular users get the error message:
Logon failed for login 'xxxx' due to trigger execution.
Changed database context to 'xxxx',
Changed language setting to us_english. (Microsoft SQL Server, Error: 17892).
Thanks
EDIT: We have just noticed that this only happens for active directory accounts, not sql accounts.
For example:
C:\>osql -S server -E
Logon failed for login 'xxx\xxxx' due to trigger execution.
C:\>osql -S server -U xxxx
Password:
1>
First of all, I would strongly recommend that you move this table to either [master] or [msdb]. Having a Logon trigger dependent on any non-system database is very problematic.
Secondly, if the current question is "How to grant rights to all logins?" as stated in your comment, then the answer is: "Grant them to the Public server role." Every login is in that role, so its permissions apply to everyone.
CREATE TRIGGER [Logon_Audit_Tgr] ON ALL SERVER
WITH EXECUTE AS 'sa'
FOR LOGON
AS
BEGIN ....

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