Connect to a server with TSQL - sql-server

Is there any way to connect to a server with t-sql?
I want to assign a shortcut to it
I already tried ':Connect -serverName ...'
Thanks for your time
Edit: I just want to do what "connect to database engine" does with SQL commands

You can set up linked servers like this:
EXEC sp_addlinkedServer N'remoteSqlServer\Instance', N'SQL Server'
EXEC sp_addlinkedsrvlogin #rmtsrvname = N'remoteSqlServer\Instance', #useself = 'FALSE',
#rmtuser = N'user', #rmtpassword = N'password'
(replace the 'remoteSqlServer\instance' name with your actual server name and instance name, and 'user' with the user to log in with, and 'password' with that user's login password)
From then on, you can reference the server using the same dot notation that you use to reference different databases on the same server:
SELECT * FROM [server\instance].[database].[schema].[tableName]
You do not have to 'connect' to these other servers in SQL Server Management Studio... you can just be on one server, and reference all the others, and mix them into your queries as you need.

Related

Created remote server link to Azure, but dbo schema is not shown

I am developing a web application which in production connects to an Azure database but in my local environment connects to a SQL Server running in Docker. I would like my local database to link to the Azure database so that I can easily copy data from production. I was able to successfully link via these commands:
EXEC sp_addlinkedserver
#server='remote',
#srvproduct='',
#provider='sqlncli',
#datasrc='mydb.database.windows.net',
#location='',
#provstr='',
#catalog='mydb';
EXEC sp_addlinkedsrvlogin
#rmtsrvname = 'remote',
#useself = 'false',
#rmtuser = 'my_username',
#rmtpassword = 'my_password';
EXEC sp_serveroption 'remote', 'rpc out', true;
...however although I can connect and am using the same username & password used by the app itself which works, I cannot see my objects in the dbo schema, only sys and INFORMATION_SCHEMA.
Why am I unable to see [remote].[mydb].[dbo].* objects when linking to a remote Azure database? I get this error when attempting to SELECT:
Msg 7314, Level 16, State 1, Line 1
The OLE DB provider "MSOLEDBSQL" for linked server "remote" does not contain the table ""mydb"."dbo"."my_table"". The table either does not exist or the current user does not have permissions on that table.
Have you looked at the table's permissions?
It appears to be a permissions problem. Your query is correct.
As a piece of advice, try connecting the server using a specific user who has been granted select permission on particular table/database.
GRANT select ON DATABASE::database_name TO username;
GO
Data from Azure sql database:
Output from Linked service:

Update the owner of SQL Server database and agent

There are a large number of objects in SQL Server that are owned by people who have resigned.
We need a script to change the ownership of all of these objects to SA.
Can anyone help with this script?
Also how we can test it before we run it in production server?
Change the owner of SQl agent job
EXEC msdb.dbo.sp_manage_jobs_by_login
#action = N'REASSIGN',
#current_owner_login_name = N'currentowner',
#new_owner_login_name = N'sa';
Change the owner of SQl Database
use master
go
select 'use [' + db.name+']; exec sp_changedbowner [sa];' from
sys.databases db left join sys.server_principals sp
on db.owner_sid=sp.sid
where suser_sname(owner_sid)='current owner'

Using sp_addlinkedserver to access a db on the same server - but with a different user

I'm trying to use another database on the same server, but my current db-user has no access to the other one.
I tried to sp_addlinkedserver-link the server to itself, so I could use sp_addlinkedsrvlogin to specify another user, but I get error messages for denied permission before I even get to the second part; I suspect because it is on the same server.
Here's what I came up with:
exec sp_addlinkedserver
#server= N'SameServer',
#srvproduct= N'SQL Server';
exec sp_addlinkedsrvlogin
#rmtsrvname= N'SameServer',
#useself= N'FALSE',
#rmtuser= N'AlternativeLogin',
#rmtpassword= N'';
The error messages tell me that the user lacks permissions for the procedure sp_MSaddserver_internal (?), as well as sp_addlinkedsrvlogin
Ultimately, I'd also like to use an alias for the connection because SameServer.dbName will be confusing, and I've found answers for doing that, but obviously, since I haven't gotten that far I can't test how that goes.
If you can run sp_addlinkedserver, then you most likely already have the permissions needed to gain access to the other database.
If you have rights to run sp_addlinkedserver, then sp_addlinkedsrvlogin would require you to know the password of "AlternativeLogin" or it has no password, ergo you don't need a linked server
Both sp_addlinkedserver and sp_addlinkedsrvlogin require elevated rights that would not typically by delegated outside the sysadmin group
Do it properly: ask your sysadmin or DBA.

SQL Server : login success but "The database [dbName] is not accessible. (ObjectExplorer)"

I am using windows 8.1 and SQL Server 2012.
I was using an OS account "Manoj" for accessing SQL SERVER with windows authentication.
Recently I have deleted my user account "Manoj" of OS and created a new account with same name "Manoj".
But the system took the new account as "Manoj_2". This change keeps me out from accessing the old databases, I have created.
It says that
The database [dbName] is not accessible. (ObjectExplorer)
whenever I try to access any of the previous DBs I have created.
I used to create new login in SQL Server for "Manoj_2", with default DB as "master". But still the problem persists.
I cannot able to detach the DBs. I am unable to expand the DBs.
Note: In OS, I have admin rights for the "Manoj" account.
Please anybody tell me, what to do? either with OS or with SQL Server
For this situation you have to connect to database in Single-User mode.
Starting SQL Server in single-user mode enables any member of the computer's local Administrators group to connect to the instance of SQL Server as a member of the sysadmin fixed server role.
Here you can find step-by-step instruction to do this.
In short you must start the sqlserver instance with parameters -m, after start Sql Server Management Studio with windows authentication.
Now you are a sysadmin, assign the sysadmin role to your user, exit and remove the -m parameter and restart sql server.
The problem is that the user in the database is an "orphan". This means that there is no login id or password associated with the user. This is true even if there is a login id that matches the user, since there is a GUID (called a SID in Microsoft-speak) that has to match as well.
This used to be a pain to fix, but currently (SQL Server 2000, SP3) there is a stored procedure that does the heavy lifting.
All of these instructions should be done as a database admin, with the restored database selected.
First, make sure that this is the problem. This will lists the orphaned users:
EXEC sp_change_users_login 'Report'
If you already have a login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user'
If you want to create a new login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user', 'login', 'password'
this text was obtained at http://www.fileformat.info/tip/microsoft/sql_orphan_user.htm in Dez-13-2017
Really stupid solution but I'll add it here in case anyone gets here from a Google search.
I'd just restarted the SQL service and was getting this error and in my case, just waiting 10 minutes was enough and it was fine again. Seems this is the error you get when it is just starting up.
If you are using Sql Management Studio, just start it as Administrator.
Right click->Run as Administrator
This is what led me to this issue and how I fixed it:
Restored my database to another SQL server instance from a .bak file, which included a preexisting user.
Tried to access the restored database from my app as usual using the same connection string but updated server instance.
Received error.
Deleted user as the DBowner, then readded with exact same credentials, mappings, login, etc.
Was able to login as the user after readding the user after the restore.
This is caused when the user's default database is set to a database they don't have permissions or its offline.
Just try to re add the user.Pleae have a look here too.
I had twoo users: one that had the sysadmin role, the other one (the problematic one) didn't.
So I logged in with the other user(you can create a new one) and checked the ckeck box 'sysadmin' from: Security --> Logins --> Right ckick on your SQL user name --> Properties --> Server Roles --> make sure that the 'sysadmin' checkbox has the check mark.
Press OK and try connecting with the newly checked user.
In my case it worked when I had opened SQL Server Management Studio with Administrator credentials and I right-clicked on the database and select "Go online" or something like this.
Please try this script.. What this script does is it looks at the active sessions of the database and kills them so you can bring the database back online.
CREATE TABLE #temp_sp_who2
(
SPID INT,
Status VARCHAR(1000) NULL,
Login SYSNAME NULL,
HostName SYSNAME NULL,
BlkBy SYSNAME NULL,
DBName SYSNAME NULL,
Command VARCHAR(1000) NULL,
CPUTime INT NULL,
DiskIO INT NULL,
LastBatch VARCHAR(1000) NULL,
ProgramName VARCHAR(1000) NULL,
SPID2 INT
, rEQUESTID INT NULL --comment out for SQL 2000 databases
)
INSERT INTO #temp_sp_who2
EXEC sp_who2
declare #kill nvarchar(max)= ''
SELECT #kill = #kill+ 'kill '+convert(varchar,spid) +';'
FROM #temp_sp_who2
WHERE DBName = 'databasename'
exec sp_executesql #kill
ALTER DATABASE DATABASENAME SET ONLINE WITH IMMEDIATE ROLLBACK
In my case, I simply had to start the application with "Run as administrator" in order to access anything. Otherwise I'd get the error you mentioned.
Get this error in this steps:
Run "Get offline".
"Get offline" was running too long, so i closed this window.
Then i got this error.
Steps to fix:
Go to "Activity monitor" and delete all connections to this db. Then DB became really offline and all is ok.
This fixed it for me:
Use [dbName]
GO
EXEC sp_change_users_login 'Auto_Fix','Manoj', null, 'Manojspassword'
GO
In my case, restarting SQL Server Service was enough to resolve the issue.
I experienced a similar problem after running a few jobs of bulk insert through a Python script on a separate machine and a separate user from the one I am logging in to SSMS.
It appears that if the Python kernel (or possibly any other connection) is interrupted in the middle of a bulk insert job without properly 'cleaning up' the mess, some sort of hanging related to user credentials and locks may happen on the SQL Server side. Neither restarting the service nor the whole machine worked for me.
The solution in my case was to take the DB offline and online.
In the SQL Server Management Studio, that is a right click on DB > tasks > take offline and then right click on DB > tasks > bring online.
My issue got resolved by restarting the MS SQL server service, simple.
I had a similar problem, for me I had to create a new user with name that I needed, in your case you should create some like this:
USE [master]
GO
/****** Object: Login [Manoj_2] Script Date: 9/5/2019 12:16:14 PM ******/
CREATE LOGIN [Manoj_2] FROM WINDOWS WITH DEFAULT_DATABASE=[master],
DEFAULT_LANGUAGE=[us_english]
GO
ALTER SERVER ROLE [sysadmin] ADD MEMBER [Manoj_2]
GO
Execute the following sentence:
EXEC rdsadmin.dbo.rds_set_database_online dbname
I performed the below steps and it worked for me:
1) connect to SQL Server->Security->logins->search for the particular user->Properties->server Roles-> enable "sys admin" check box
I just restarted my SQL Server (MSSQLSERVER) with which my SQL Server Agent (MSSQLSERVER) also got restarted. Now am able to access the SQL SERVER 2008 R2 database instance through SSMS with my login.
Issue: The database [dbName] is not accessible. (ObjectExplorer) got the error when expanding the database.
Solution: Deattach the database > Drop Option
Attach the database again with the mdf file under the mssql data folder
Go to
Security >> Logins >>
Right click to the user >> Properties >>
On the left navigation move to >> User Mapping >> Check the database and in the "Database role membership for: <>" check "db_owner" for user that you are experience the issue.
PROBLEM SOLVED...

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

Resources