SQL SERVER - how can I rollback "use [MASTER]" query - sql

I accidentally ran query Change authentication mode (T-SQL) in sql server:
USE [master]
GO
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE',
N'Software\Microsoft\MSSQLServer\MSSQLServer',
N'LoginMode', REG_DWORD, 1
GO
Now I can't work with SQL SERVER.

You can change it back using below code:
EXEC xp_instance_regwrite
N'HKEY_LOCAL_MACHINE',
N'Software\Microsoft\MSSQLServer\MSSQLServer',
N'LoginMode',
REG_DWORD,
2; -- only difference is right here
You have changed authentication mode to windows only. So now you have to log in using windows account then you can change the authentication mode to mixed mode again. Or you can edit your registry to do so. Please check below link:
https://www.top-password.com/knowledge/sql-server-authentication-mode.html

Related

Can not run cmdshell #command in SQL Server Express

I can not run cmdshell #command commands in my SQL Server Express. Is it something to do with the SQL Server version? Should I have to have like SQL Server Standard edition to run this command?
Enable it, as described in the Microsoft article:
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1;
GO
-- To update the currently configured value for advanced options.
RECONFIGURE;
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1;
GO
-- To update the currently configured value for this feature.
RECONFIGURE;
GO
It was a permission issue which is fixed now! Thank you all for the help!

Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server

I'm trying to establish a linked server from SQL Server 2008 R2 to an Access database. The Access database is not password protected. As I have seen in other posts (specifically this one), this is usually due to the current user not having access to the Temp folder inside the NetworkService folder. Since we are running this in Windows Server 2008, the directory structure is quite different than what most are eluding to. I have allowed access to every temp folder in the "root:\Documents and Settings\" directory, and to no avail.
This is the procedure I am using to add the linked server:
EXEC sp_addlinkedserver
#server = N'OS_Access',
#provider = N'Microsoft.ACE.OLEDB.12.0',
#srvproduct = N'',
#datasrc = N'C:\RTBData\Data\OS.mdb';
GO
It creates the linked server with no problem, but I am not able to view the tables/views of the database. Likewise, my ASP.NET application cannot access it either.
I have tried both ACE and JET(64-bit)(by installing the Data Connectivity Components for Office), and they both do not work. I have also tried configuring the ACE provider with "Dynamic Parameter" and "Allow InProcess" to true.
Additionally, I tried upping the memory usage by the MSSQLSERVER services by adding "-g512;" in front of "startup parameters" string in SQL configuration manager to rule out memory issues.
If anyone could shed some light on this that would be fantastic! Thanks!
UPDATE: I logged into SQL using the sa account, and I was able to view the linked server. My current user account has full permissions in SQL server, so I am unsure of what the difference is between the accounts. Maybe I gave permissions to the wrong Temp folder, in which the sa account (being built-in) has access to. If someone could point me in the right direction here, that would be great, and I think it would also help a lot of other people.
I fixed the problem by disabling UAC within the control panel. I am unsure what changes this made, but it might help others!
USE [master]
GO
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO
USE [master]
GO
EXEC master . dbo. sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'AllowInProcess' , 1
GO
EXEC master . dbo. sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'DynamicParameters' , 1
GO
SELECT *
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0','Name & Location of DB';;, [TableName])

how can i access a file/folder over network through XP_CMDSHELL in sql server 2008?

I am trying to access a folder/directory using 'EXEC MASTER..XP_CMDSHELL' it works for the local file/folder, how ever it can not access the folder over network.
EXEC MASTER..XP_CMDSHELL 'c:\Images' --Works fine
EXEC MASTER..XP_CMDSHELL '\\IPaddress\Images' -- returns "Access is denied."
Please note that i can access the network location but not using sql server.
Sql server is running under Winodws Authentication mode.
Sql server is using 'nt authority\network service' account to access the remote Folder.
Regards
If you run xp_cmdshell 'whoami.exe' it will tell you the account the command is running under. If this account doesn't have permissions on the network, you'll get the error you are seeing.
Check the SQL documentation for changing this account/permissions.
When you have to put file, like BCP result, or a backup in a remote drive, just map this drive into windows don't work, it must be mapped on SQL Server to!, to do this, try some link like this:
exec xp_cmdshell 'net use p:\ \Server\Folder\Folder\Folder\ /Domain\Login /Password'
Reference : https://social.msdn.microsoft.com/Forums/en-US/6eca2d62-eb86-4f23-9b86-6f917017f50c/bcp-utility-via-xpcmdshell-and-network-drive?forum=sqlsecurity

SQL Server Script to create a new user

I want to write a script to create a admin user ( with abcd password ) in SQL Server Express.
Also I want to assign this user admin full rights.
Based on your question, I think that you may be a bit confused about the difference between a User and a Login. A Login is an account on the SQL Server as a whole - someone who is able to log in to the server and who has a password. A User is a Login with access to a specific database.
Creating a Login is easy and must (obviously) be done before creating a User account for the login in a specific database:
CREATE LOGIN NewAdminName WITH PASSWORD = 'ABCD'
GO
Here is how you create a User with db_owner privileges using the Login you just declared:
Use YourDatabase;
GO
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'NewAdminName')
BEGIN
CREATE USER [NewAdminName] FOR LOGIN [NewAdminName]
EXEC sp_addrolemember N'db_owner', N'NewAdminName'
END;
GO
Now, Logins are a bit more fluid than I make it seem above. For example, a Login account is automatically created (in most SQL Server installations) for the Windows Administrator account when the database is installed. In most situations, I just use that when I am administering a database (it has all privileges).
However, if you are going to be accessing the SQL Server from an application, then you will want to set the server up for "Mixed Mode" (both Windows and SQL logins) and create a Login as shown above. You'll then "GRANT" priviliges to that SQL Login based on what is needed for your app. See here for more information.
UPDATE: Aaron points out the use of the sp_addsrvrolemember to assign a prepared role to your login account. This is a good idea - faster and easier than manually granting privileges. If you google it you'll see plenty of links. However, you must still understand the distinction between a login and a user.
Full admin rights for the whole server, or a specific database? I think the others answered for a database, but for the server:
USE [master];
GO
CREATE LOGIN MyNewAdminUser
WITH PASSWORD = N'abcd',
CHECK_POLICY = OFF,
CHECK_EXPIRATION = OFF;
GO
EXEC sp_addsrvrolemember
#loginame = N'MyNewAdminUser',
#rolename = N'sysadmin';
You may need to leave off the CHECK_ parameters depending on what version of SQL Server Express you are using (it is almost always useful to include this information in your question).
You can use:
CREATE LOGIN <login name> WITH PASSWORD = '<password>' ; GO
To create the login (See here for more details).
Then you may need to use:
CREATE USER user_name
To create the user associated with the login for the specific database you want to grant them access too.
(See here for details)
You can also use:
GRANT permission [ ,...n ] ON SCHEMA :: schema_name
To set up the permissions for the schema's that you assigned the users to.
(See here for details)
Two other commands you might find useful are ALTER USER and ALTER LOGIN.
If you want to create a generic script you can do it with an Execute statement with a Replace with your username and database name
Declare #userName as varchar(50);
Declare #defaultDataBaseName as varchar(50);
Declare #LoginCreationScript as varchar(max);
Declare #UserCreationScript as varchar(max);
Declare #TempUserCreationScript as varchar(max);
set #defaultDataBaseName = 'data1';
set #userName = 'domain\userName';
set #LoginCreationScript ='CREATE LOGIN [{userName}]
FROM WINDOWS
WITH DEFAULT_DATABASE ={dataBaseName}'
set #UserCreationScript ='
USE {dataBaseName}
CREATE User [{userName}] for LOGIN [{userName}];
EXEC sp_addrolemember ''db_datareader'', ''{userName}'';
EXEC sp_addrolemember ''db_datawriter'', ''{userName}'';
Grant Execute on Schema :: dbo TO [{userName}];'
/*Login creation*/
set #LoginCreationScript=Replace(Replace(#LoginCreationScript, '{userName}', #userName), '{dataBaseName}', #defaultDataBaseName)
set #UserCreationScript =Replace(#UserCreationScript, '{userName}', #userName)
Execute(#LoginCreationScript)
/*User creation and role assignment*/
set #TempUserCreationScript =Replace(#UserCreationScript, '{dataBaseName}', #defaultDataBaseName)
Execute(#TempUserCreationScript)
set #TempUserCreationScript =Replace(#UserCreationScript, '{dataBaseName}', 'db2')
Execute(#TempUserCreationScript)
set #TempUserCreationScript =Replace(#UserCreationScript, '{dataBaseName}', 'db3')
Execute(#TempUserCreationScript)
CREATE LOGIN AdminLOGIN WITH PASSWORD = 'pass'
GO
Use MyDatabase;
GO
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'AdminLOGIN')
BEGIN
CREATE USER [AdminLOGIN] FOR LOGIN [AdminLOGIN]
EXEC sp_addrolemember N'db_owner', N'AdminLOGIN'
EXEC master..sp_addsrvrolemember #loginame = N'adminlogin', #rolename = N'sysadmin'
END;
GO
this full help you for network using:
1- Right-click on SQL Server instance at root of Object Explorer, click on Properties
Select Security from the left pane.
2- Select the SQL Server and Windows Authentication mode radio button, and click OK.
3- Right-click on the SQL Server instance, select Restart (alternatively, open up Services and restart the SQL Server service).
4- Close sql server application and reopen it
5- open 'SQL Server Configuration Manager' and tcp enabled for network
6-Double-click the TCP/IP protocol, go to the IP Addresses tab and scroll down to the IPAll section.
7-Specify the 1433 in the TCP Port field (or another port if 1433 is used by another MSSQL Server) and press the OK
8-Open in Sql Server: Security And Login And Right Click on Login Name And Select Peroperties And Select Server Roles And
Checked The Sysadmin And Bulkadmin then Ok.
9-firewall: Open cmd as administrator and type:
netsh firewall set portopening protocol = TCP port = 1433 name = SQLPort mode = ENABLE scope = SUBNET profile = CURRENT
This past week I installed Microsoft SQL Server 2014 Developer Edition on my dev box, and immediately ran into a problem I had never seen before.
I’ve installed various versions of SQL Server countless times, and it is usually a painless procedure. Install the server, run the Management Console, it’s that simple. However, after completing this installation, when I tried to log in to the server using SSMS, I got an error like the one below:
SQL Server login error 18456
“Login failed for user… (Microsoft SQL Server, Error: 18456)”
I’m used to seeing this error if I typed the wrong password when logging in – but that’s only if I’m using mixed mode (Windows and SQL Authentication). In this case, the server was set up with Windows Authentication only, and the user account was my own. I’m still not sure why it didn’t add my user to the SYSADMIN role during setup; perhaps I missed a step and forgot to add it. At any rate, not all hope was lost.
The way to fix this, if you cannot log on with any other account to SQL Server, is to add your network login through a command line interface. For this to work, you need to be an Administrator on Windows for the PC that you’re logged onto.
Stop the MSSQL service.
Open a Command Prompt using Run As Administrator.
Change to the folder that holds the SQL Server EXE file; the default for SQL Server 2014 is “C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Binn”.
Run the following command: “sqlservr.exe –m”. This will start SQL Server in single-user mode.
While leaving this Command Prompt open, open another one, repeating steps 2 and 3.
In the second Command Prompt window, run “SQLCMD –S Server_Name\Instance_Name”
In this window, run the following lines, pressing Enter after each one:
1
CREATE LOGIN [domainName\loginName] FROM WINDOWS
2
GO
3
SP_ADDSRVROLEMEMBER 'LOGIN_NAME','SYSADMIN'
4
GO
Use CTRL+C to end both processes in the Command Prompt windows; you will be prompted to press Y to end the SQL Server process.
Restart the MSSQL service.
That’s it! You should now be able to log in using your network login.

Connect to remote server in T-SQL (SQL server 2008)

Does anyone have an example of a stored procedure which makes a connection to a remote server?
I have been searching the web and have so far discovered that it might can be done using sp_addlinkedserver and sp_addlinkedsrvlogin but I haven't found a good example and I don't understand the documentation that well.
UPDATE:
None of the two first replies help me out, the closest I can get is using this:
EXEC sp_addlinkedserver
#server = 'SiminnSrv',
#provider = 'SQLNCLI',
#catalog = 'devel',
#srvproduct = '',
#provstr = 'DRIVER={SQL Server};SERVER=my.serveradr.com;UID=my_user_name;PWD=my_pass_word;'
That actually makes me connect but when I query a table I get this message:
Login failed for user '(null)'. Reason: Not associated with a trusted SQL Server >connection.
Essentially you create a linked server to the other server, and then provide login credentials to be used for SQL calls to that linked server. e.g. this will connect to "MyOtherServer" using a DomainAccount for that server with the username & password 'DomainUserName', 'DomainPassword'
EXEC sp_addlinkedserver 'MyOtherServer', N'SQL Server'
EXEC sp_addlinkedsrvlogin
'MyOtherServer',
'false',
'OtherServerDomain\DomainUser',
'DomainUserName',
'DomainPassword'
More Info Here And Here
I managed to connect to MSSQL Server 2008 through a linked server using the "SQL Server Native Client 10" (SQLNCLI10), but I had to use sp_addlinkedsrvlogin instead of #provstr to provide the connection details. This is based on the example from this article:
EXEC master.dbo.sp_addlinkedserver
#server = 'MyServerConnection',
#srvproduct = '',
#datasrc = 'SERVERNAME\INSTANCENAME',
#provider = 'SQLNCLI10',
#provstr = ''
EXEC sp_addlinkedsrvlogin
#rmtsrvname = 'MyServerConnection',
#useself = 'false',
--#locallogin = 'someLocalUser' -- Use to restrict the connection to specific login
#rmtuser = 'remoteUser',
#rmtpassword = 'secret'
Querying this linked server:
SELECT *
FROM [MyServerConnection].[SomeDatabase].[dbo].[TableName]
I may be late to the party, but I found the following links worked for me:
To perform the intial link, I used
EXEC sp_addlinkedserver #server='serverLinkPseudonym',#srvproduct='',#provider='SQLOLEDB', #datasrc='192.168.1.1';
Then, as I was logging in with Windows authentication, I added the Windows user (this cured my " Not associated with a trusted SQL Server" error)
EXEC sp_addlinkedsrvlogin 'serverLinkPseudonym', 'false', 'MACHINENAME\windowsLogin', 'lnkSrvLogin', 'lnkSrvPswd';
I also found that if I was going to run SQL Server Agent jobs that made calls to the LinkedServer, I had to add the following:
EXEC sp_addlinkedsrvlogin 'serverLinkPseudonym', 'false', 'NT AUTHORITY\SYSTEM', 'lnkSrvLogin', 'lnkSrvPswd';
For the sake of clarity:
"192.168.1.1" is the IP of the server to be linked to.
"lnkSrvLogin" is a login on the server to be linked to, that has access to the database(s) that you need to access.
"lnkSrvPswd" is the password of that account.
If you are connecting to the linked server, using an account from the existing server, then you just use that account name in the sp_addlinkedsrvlogin command. eg:
EXEC sp_addlinkedsrvlogin 'serverLinkPseudonym', 'false', 'thisServerLogin', 'lnkSrvLogin', 'lnkSrvPswd';
Then test it:
SELECT * FROM [serverLinkPseudonym].[DBName].[dbo].[TableName]
IF you want to be able to query another server, you will need to create a linked server.
This page has a pretty thorough explination of how the sp works.
http://doc.ddart.net/mssql/sql70/sp_adda_17.htm
if you want to link to antoher sql server, just execute this:
sp_addlinkedserver #server='ServerName', #srvproduct='SQL Server'
#server is the name of the server you want to add. #srcproduct is the type of server it is. there might be some other things you'll have to do to hook up 2008 to 2005, but 2008 should work like this.