Microsoft SQL Server, Error 916 - sql

I'm using Microsoft SQL Server 2012 Management Studio Express. I have detached one of my databases (it was in my office server) and .mdf and .ldf files are saved to MSSQL folder (on my local server). While I was detaching the database it was saying that with my connections (hopefully the server) cannot detach the database. Then I selected the drop connections option in the detach mode.
Now when I try to attach the database it doesn't allow me to attach. When I click the add button doesn't give me the option to browse my folder. Below error message is showing.
Failed to retrieve data for this request.(Microsoft.SqlServer.Management.Sdk.Sfc)
Additional information:
An exception occurred while executing a Transact-SQL statement or batch.(Microsoft SQL server. connectionInfo).
The server principal "my username" is not able to access the database "model" under the current security context.(Microsoft SQL server, Error:916).
What should I do? Please help me.

To resolve the issue... follow the given steps.
(1) Start sqlserver and login
(2) Press "F7" or click on "View->Object Explorer Details" to open Object Explorer Details window.
(3) You will see there column header.. like "Name", "Policy Health State", "Recovery Model", "Collation" etc.
(4) Right click on the header and unselect the "Collation".
(5) Now refresh the database folder. You will get all database list.

It's not a problem with the actual attach statement, but rather with setting up the wizard UI (which is a shame IMO). Use T-SQL to attach the database instead:
create database MyDatabase
on
(filename = 'c:\Data\mydatabase_data.mdf'),
(filename = 'c:\Data\mydatabase_log.ldf')
for attach;
You'd be better off to use T-SQL all the time instead of SSMS wizards. Or use wizard to script out the action and execute in a query window.
Also, check what's the problem with the permissions on model. Use this query to see if there's any DENY:
use model;
go
select
user_name(p.grantee_principal_id),
dp.principal_id,
dp.type_desc as principal_type_desc,
p.class_desc,
object_name(p.major_id) as object_name,
p.permission_name,
p.state_desc as permission_state_desc
from sys.database_permissions p
inner join sys.database_principals dp
on p.grantee_principal_id = dp.principal_id
where p.state_desc = 'DENY'

Related

Import Excel 2010 to Sql Server 2008

I am using Excel 2010 and sql server 2008 to import the data from excel to sql server. But am unsuccessful. Can you please check the way i am doing ?
sp_CONFIGURE 'show advanced options',1
RECONFIGURE
GO
sp_CONFIGURE 'optimize for ad hoc workloads',1
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;Database=C:\Users\anayak\AppData\Roaming\Microsoft\Templates\Book1.xlsx; HDR=YES;IMEX=1','SELECT * FROM [sheet1$]');
where i am getting this error
OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "Unspecified error".
Msg 7303, Level 16, State 1, Line 1
Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".
I installed the Microsoft Access Database Engine 2010 Redistributable for Microsoft.ACE.OLEDB.12.0.
But when i use the command "ODBCAD32.EXE" to check the version of my excel then i am getting 14.00.4760.1000.
Then i tried my connection string to -
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.14.0','Excel 14.0;Database=C:\Users\anayak\AppData\Roaming\Microsoft\Templates\Book1.xlsx; HDR=YES;IMEX=1','SELECT * FROM [sheet1$]');
but again it didnt work.
Can you please suggest what i am doing wrong here ?
Thanks.
Re: 7303 error
Distributed Queries in SQL Server, data from XLS
So your main error is likely this;
OLE DB provider "MICROSOFT.JET.OLEDB.4.0" for linked server "(null)" returned message "Unspecified error".
Msg 7303, Level 16, State 1, Line 1
Cannot initialize the data source object of OLE DB provider "MICROSOFT.JET.OLEDB.4.0" for linked server "(null)".
I would check some permissions.
Check the permissions on the Temp folder
This is needed because the provider uses the temp folder while retrieving the data. The folder can be one of the below based on whether you use a local system account or network domain account.
For network accounts, folder is
\Windows\ServiceProfiles\NetworkService\AppData\Local\Temp
and for local system account its \Windows\ServiceProfiles\LocalService\AppData\Local\Temp
Right click on this folder and give it read write access to the account (or group) executing the code. That solved the error for me.
Also
http://blogs.msdn.com/b/spike/archive/2008/07/23/ole-db-provider-microsoft-jet-oledb-4-0-for-linked-server-null-returned-message-unspecified-error.aspx
This is because the SQL Server Service is trying to write the temp DSN to the temp folder for the login that started the service, in this case the Admin/Admin login.
The temp folder is something like: C:\Documents and Settings\Admin\Local Settings\Temp
.15 As mentioned, the OleDbProvider will always execute in the context of the user who initialized it, in this case User/User.
.16 User/User has no rights on this folder (C:\Documents and Settings\Admin\Local Settings\Temp).
If running FileMon when the SQL is executed, we can see the following:
(Actually, try using Process Monitor - http://technet.microsoft.com/en-us/sysinternals/bb896645)
sqlservr.exe:000 QUERY INFORMATION C:\DOCUME~1\Admini~1\LOCALS~1\Temp ACCESS DENIED Attributes: Error
So to summarize so far:
The SQL Server service is started as Admin/Admin, when the select is made, the OleDb provider is invoked by User/User.
Now the OleDb provider attempts to create a temporary DSN in the temp directory. This will be the temp directory for the SQL Server service (Admin/Admin)
but the user (in this case User/User) does not have write permissions on this folder. And the error occurs.
There are two ways to resolve this.
Option 1:
Log out of the machine and log in as the account that starts the SQL Server Service (in this case Admin/Admin) then start a command prompt
and type “set t” (no quotes), this will show something like:
TEMP=C:\DOCUME~1\Admin\LOCALS~1\Temp
TMP=C:\DOCUME~1\Admin\LOCALS~1\Temp
these are the environment variables set for %TEMP% and %TMP%, so go to that folder and right click and select Properties -> Security,
then add the user, in this case User/User, note that the default for the user is Read&Execute/List Folder Content/Read, this not enough, you have to select Write as well.
Log out, and log in again as User/User and rerun the command from SSMS. This time it should work.
Option 2:
Log on as Admin and change the TEMP and TMP variable to, for example, C:\Temp, basically this moves the Temp directory out of the Documents and Settings folder.
However, you must restart the SQL server for this to take effect.
So basically, what happens is that when SQL Server starts, it uses the Temp folder of the startup account (Admin/Admin) but the MICROSOFT.JET.OLEDB.4.0 will always execute
as the user who calls the SQL command (User/User) and this will fail unless this user does not have Write access to that temp folder.
Without knowing all setups out there, perhaps option 2 is the preferred solution since with option 1, you will have to add ALL the users that will invoke the provider which may not be practical.
Also, when changing the startup account for the SQL Server service, then the TEMP directory for that account will be used, and you will see the error again until you, again, give write permissions for all the users on this TEMP folder...or a user group (preferred).

SQL Server Management Studio connection defaults to 'master' when selecting a database-specific object

In SQL Server 2008 R2 Management Studio, if I right-click on an object inside a specific database and choose "Select top 1000 rows ..", the database connection for the query window always opens on 'master' while the table name is fully qualified as [database].[dbo].[table]. This makes it impossible to jump in and tweak out this query and insert joins, etc., to the statement without also fully-qualifying everything I add, or add a USE statement, or select the database from the drop-down menu.
Is there a setting or something that will make query windows open with a database connection of the selected object browser's database rather than connect to 'master', and not fully qualify the object's database in the query text? I realize that I can register my SQL connection to default to my database, but we actually go through multiple new databases every week--in a given month I will have touched tens of databases--so it would be difficult to manage multiple database registrations. I would rather it if SSMS just connected to the specified database. Possible and straightforward?
If you are going in via Win Auth, are in a group, are using SA or some other userid, or are in a situation where changing your login is not really the solution, AND if all you wish to do is default to a database in the query editor:
In an existing open query editor, right-click, select Connection, Change Connection.
Click the Options button to expand the options.
In the Connection Properties tab, select the database you wish to connect to.
SSMS will remember your selection for that server. You may have to repeat for other servers, but it does remedy having a default database other than master.
There is no such setting for the SELECT TOP command, but you may be able to do this by changing the default database for your login. This is tedious if you're doing this often for various databases (much like changing the registrations, as I just noticed you already outlined).
Instead of using SELECT TOP 1000 (which in addition to not putting you in the right database context, also puts a TOP in that I assume you're just going to remove as well), you should right-click the table and choose Script Table as > SELECT to > New Query Window. This puts the context in the right DB, adds a USE command, doesn't have a TOP and doesn't database-prefix the table name.
If you want query window connects to some database by default, in SSMS go to the Security -> Logins, select the login that you use to connect to this server, and loock at the properties window. In page 'general' change the default database from 'master' to database you want to connect.
You could just put a USE [database name] at the top of the query window prior to executing a query. You do not need to fully qualify the database names if you do this. If you generate any scripts and version control them, this is a good practice to put at the top anyway. It at least prevents executing the script erroneously against the wrong database (say creation of a stored procedure).
USE MySpecialDatabase
GO
SELECT * FROM MySpecialTable

Problem creating database using SQL Server Management Express

I am trying to create a database using SQL Server Management Express.
The following error occurs:
TITLE: Microsoft SQL Server Management
Studio Express
Create failed for Database
'dbTestDBase'.
(Microsoft.SqlServer.Express.Smo)
For help, click:
http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=9.00.2047.00&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Create+Database&LinkId=20476
ADDITIONAL INFORMATION:
An exception occurred while executing
a Transact-SQL statement or batch.
(Microsoft.SqlServer.Express.ConnectionInfo)
CREATE DATABASE permission denied in
database 'master'. (Microsoft SQL
Server, Error: 262)
For help, click:
http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=09.00.1399&EvtSrc=MSSQLServer&EvtID=262&LinkId=20476
Run Microsft SQL Server Studio as administrator....your problem will be solved
It's very clear: the credential you are using doesn't have enough privileges to be able to create a new database. Are you logged in using Integrated Windows Authentication or Sql Server Authentication? Make sure your credentials have the dbcreator role either way.
http://msdn.microsoft.com/en-us/library/ms176014%28v=SQL.90%29.aspx
If the computer is part of Domain. Log-in as local administrator account on the work station (maybe because the MSQSQL is installed on the computer using local administrator account, means that the local administrator account has systemadmin access on SMSQL), then when you are already logged as local administrator. open the MSSQL , now add/edit MSSQL security account.
I had this same problem. but solved!
you should go to your specify folder where database created (ex:C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\DATA)
then right click on data folder -> properties-> advanced
then uncheck compress content to save disk space.
that's it.
Well, the error message seems to be pretty clear:
CREATE DATABASE permission denied in
database 'master'.
Obviously, the user account you're using doesn't have the permission to create a new database. Is that possible? What kind of user are you using?
Also: can you show us the CREATE DATABASE statement you're using??
Just check whether path is specified or not
For example : "C:..\MSSQL\DATA", in both the columns of Database files in the New Database wizard
I hope this solution will help someone!
My problem started when I had deleted the previous user from PC Management and from registry. Then I create a fresh-std user. and trying to create database from the new user, and that's where my problem started.
After searching for the better solution, I conclude by Uninstalling MS Server Express Database completely from my PC and re-install it again. This save time and solved my problem.
I hope this solution helps someone too!
I had similar issue and was solved by executing below command
--Step1 Find if it is used by some other PID
Use
master
GO
IF
EXISTS(SELECT request_session_id FROM
sys.dm_tran_locks
WHERE resource_database_id =
DB_ID('Model'))
PRINT
'Model Database being used by some other session'
ELSE
PRINT
'Model Database not used by other session'
-- Step 2 - Identify
SELECT request_session_id FROM
sys.dm_tran_locks
-- Step 3 Get PID
WHERE resource_database_id =
DB_ID('Model')
-- Step 4 Get the EventInfo
DBCC InputBuffer(214)
-- Step 5 Kill the PID
Kill 214
Hope this helps
I had the same problem when trying to create the database with Right Click + New Database on Databases.
The solve was using New Query and the command to create database:
CREATE DATABASE databasename;
In the end I want to mention that I was logged in Management Studio with (localdb)\v11.0 over windows authentication.

How to remove "Server name" items from history of SQL Server Management Studio

When trying to connect to a server in Management Studio (specifically 2008), there is a field where you enter the Server name. That field also has a drop-down list where it shows a history of servers that you have attempted to connect to.
How to remove an individual item
from that history?
How to remove an
item from the Login field history
for each Server name?
As of SQL Server 2012 you no longer have to go through the hassle of deleting the bin file (which causes other side effects). You should be able to press the delete key within the MRU list of the Server Name dropdown in the Connect to Server dialog. This is documented in this Connect item and this blog post.
Note that if you have multiple entries for a single server name (e.g. one with Windows and one with SQL Auth), you won't be able to tell which one you're deleting.
Here is simpliest way to clear items from this list.
Open the Microsoft SQL Server Management Studio (SSMS) version you want to affect.
Open the Connect to Server dialog (File->Connect Object Explorer, Object Explorer-> Connect-> Database Engine, etc).
Click on the Server Name field drop down list’s down arrow.
Hover over the items you want to remove.
Press the delete (DEL) key on your keyboard.
there we go.
For SQL 2005, delete the file:
C:\Documents and Settings\<USER>\Application Data\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat
For SQL 2008, the file location, format and name changed:
C:\Documents and Settings\<USER>\Application Data\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin
How to clear the list:
Shut down all instances of SSMS
Delete/Rename the file
Open SSMS
This request is registered on Microsoft Connect
Over on this duplicate question #arcticdev posted some code that will get rid of individual entries (as opposed to all entries being delete the bin file).
I have wrapped it in a very ugly UI and put it here: http://ssmsmru.codeplex.com/
For SQL Server 2012 Management Studio, this file has moved. It is now located at:
C:\Users\<username>\AppData\Roaming\Microsoft\
SQL Server Management Studio\11.0\SqlStudio.bin
In Windows Server 2008 standard with SQL Express 2008, the "SqlStudio.bin" file lives here:
%UserProfile%\Microsoft\Microsoft SQL Server\100\Tools\Shell\
Here is an easy way.
Open the connection window, click on the Server name dropdown, and hover over the connection string you want to delete, then press delete.
Delete the file from above path: (Before delete please close SSMS)
File location path for the users of SQL Server 2005,
C:\Documents and Settings\%USERNAME%\Application Data\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat
File location path for the users of SQL Server 2008,
Note: Format Name has been changed.
C:\Documents and Settings\%USERNAME%\Application Data\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin
File location path for the users of Server 2008 standard/SQL Express 2008
C:\Documents and Settings\%USERNAME%\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin
File location path for the users of SQL Server 2012,
C:\Users\%USERNAME%\AppData\Roaming\Microsoft\SQL Server Management Studio\11.0\SqlStudio.bin
File location path for the users of SQL Server 2014,
C:\Users\%USERNAME%\AppData\Roaming\Microsoft\SQL Server Management Studio\12.0\SqlStudio.bin
Note: In SSMS 2012 (Version 10.50.1600.1 OR Above), ow you can remove the server name by selecting it from dropdown and press DELETE.
In SSMS 2012 there is a documented way to delete the server name from the "Connect to Server" dialog. Now, we can remove the server name by selecting it in the dialog and pressing DELETE.
File SqlStudio.bin actually contains binary serialized data of type "Microsoft.SqlServer.Management.UserSettings.SqlStudio".
Using BinaryFormatter class you can write simple .NET application in order to edit file content.
From the Command Prompt (Start \ All Programs \ Accessories \ Command Prompt):
DEL /S SqlStudio.bin
This is the correct way of doing it
http://blogs.msdn.com/b/managingsql/archive/2011/07/13/deleting-old-server-names-from-quot-connect-to-server-quot-dialog-in-ssms.aspx
For Windows Vista and SQL Server 2005,
Delete this file, or open it with the Notepad and clear the server names that you want Clear from the history
%UserProfile%\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat
C:\Users\\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell
Rather than deleting or renaming this file:
Close SQL Server Management Studio.
Find the appropriate file (see the other posts).
Open the .bin in a text/hex editior like NotePad++.
Search for the name of one of the servers and identify the line number.
Make a copy of the .bin/.dat file.
Delete that line. Make sure you delete the entire line, it's possible if you have many the line could wrap.
Open SQL Server Management Studio. Your dropdown will be blank.

how to access sql server from asp page

We have a legacy, homegrown timesheet system (ASP, microsoft sql server 2005) that I need to clone to another computer for backup purposes. (I know very little about this stuff, so pleas be gentle)
I've got most of the pieces in place (IIS, Sql Server, table import / creation). But, the ASP page to access the timesheet pages is choking on access to the sql server.
here is the line it's crashing on: conn.open Session("sConnStr")
This is the connection string;
sConnStr = "Server=MYSERVER-D01;DATABASE=MYDATABASE;UID=MyDatabaseUser;PWD=MyDatabaseUser;QuotedID=No;DRIVER={SQL Server};Provider=MSDASQL"
This is the error:
Error Type: Microsoft OLE DB Provider for ODBC Drivers (0x80004005) [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified /mydir/mypage.asp, line 17 <== shown above
Note that am able to access the db on SQL Server with Windows specified as the authentication using Server Management Studio. However, when i try using SQL Authentication, I get the message "The user is not associated with a trusted SQL connection".
Questions:
How do you set up the user / password on SQL Server 2005?
What is the default driver, and do i need to get it/set it up?
When it talks about the data source name ( see "MYDATABASE" in the
above mentioned connection string), is it talking about one of the
entries you see under "Databases" on the management studio object
explorer?
Thanks for you responses! So far, no luck. I've managed to access the database via management studio object explorer, by doing this;
Enable SQL Authentication:
....Solution
To resolve this issue, follow the instructions to set User Authentication.
SQL Server 2000:
Go to Start > Programs > Microsoft SQL Server > Enterprise Manager
Right-click the Server name, select Properties > Security
Under Authentication, select SQL Server and Windows
The server must be stopped and re-started before this will take effect
SQL Server 2005:
Go to Start > Programs > Microsoft SQL Server 2005 > SQL Server Management Studio
Right-click the Server name, select Properties > Security
Under Server Authentication, select SQL Server and Windows Authentication Mode
The server must be stopped and re-started before this will take effect..."
And
this;
Change the owner to the one being used to access the db
Microsoft SQL Server Management Studio
Right click the DB, change the owner
But I'm still getting exactly the same error message!
To create a new user and assign it to a database you'll need to do the following,
In SQL Server Management Studio, open Object Explorer and expand the
folder of the server instance in which
to create the new login.
Right-click the Security folder, point to New, and then click Login.
On the General page, enter a name for the new login in the Login name
box.
Select SQL Server Authentication. Windows Authentication is the more
secure option.
Enter a password for the login.
Select the password policy options that should be applied to the new
login. In general, enforcing password
policy is the more secure option.
Click OK.
You will then want to assign that login to a database by creating a new database user,
In SQL Server Management Studio, open Object Explorer and expand the
Databases folder.
Expand the database in which to create the new database user.
Right-click the Security folder, point to New, and then click User.
On the General page, enter a name for the new user in the User name box.
In the Login name box, enter the name of a SQL Server login to map to
the database user.
Click OK.
You'll want to make that user the db_owner. Run the following against your database.
sp_addrolemember #rolename = 'db_owner', #membername = 'usernamehere'
Then use the following connection string format to connect to the database.
Data Source=ServerAddress;Initial Catalog=DatabaseName;User Id=UserName;Password=UserPassword;
If you have a trusted connection from the login that IIS is using the the machine that has SQL Server running on it I would avoid using Username / Password and declare that the connection is trusted in your connection string:
sConnStr = "Server=MYSERVER-D01;DATABASE=MYDATABASE;UID=MyDatabaseUser;PWD=MyDatabaseUser;QuotedID=No;DRIVER={SQL Server};Provider=MSDASQL;Integrated Security=SSPI"
This is to illustrate the change, but in practice you may need to vary the connections string a bit more than that, have a look at http://www.connectionstrings.com/sql-server-2005 for examples.
When it talks about the data source name ( see "MYDATABASE" in the above mentioned connection string), is it talking about one of the entries you see under "Databases" on the management studio object explorer
Yes, your entry for "MYDATABASE" should be the exact name of the database that you see under "Databases". Make sure that you have the "Server" correct too.
Microsoft OLE DB Provider for ODBC Drivers error '80004005'
[Microsoft][ODBC Driver Manager]Data source name not found and no default driver specified.
This usually happens in one of the following scenarios:
* you referenced your connection incorrectly (e.g. spelled the DSN name, or one of the DSN-less string components wrong);
* you referenced a DSN that doesn't exist;
* the user connecting to the DSN or DSN-less connection doesn't have access to the information stored in the registry (see KB #306345);
* you used an English or localized driver detail for your connection string when your system is not set up in that language (see KB #174655); or,
* you are missing the connection string entirely (this can happen if you maintain your connection string in a session variable, and your sessions aren't working; see Article #2157).
Here is the link to the above article (note it is extremely detailed).
link
To answer the last question, MYDATABASE is calling a database by name. If you use 'MYDATABASE' in your string, you will need a database named 'MYDATABASE' in SQL Server.
This connection string should work fine with ASP if this is a SQL server. Replace your values before using obviously.
sConnStr = "provider=SQLOLEDB;Data Source=YourServerName;Initial Catalog=YourDBName;UID=YourUserName;PWD=YourUserPWD;"
The easiest way I have found to deal with these issue is to create a udl file. On your desktop create a new text file and rename it filename.udl. Double click the udl file. Click the Provider Tab > select Microsoft OLE DB Provider for SQL Server > Next. Using the connection tab you should be able to connect to your database. Once test connection succeeds click ok. You can now open the file in a text editor and copy and paste the line that start Provider... to your asp file. You should end up with sConnStr = "Provider..textfromUDLfile"
MSDN - Creating and Configuring Universal Data Link (.udl) Files
I suggest that you create a DAL (Data Access Layer) that can do all the connection stuff for you. Just passit your command an dit can open and close your conenctions and such. In any app you wan tto abstract these different layers as much as posible and that means that your aspx page should call to an object when has the methods that hten get handled by the dal and make the database calls.
Here is the format for connection to the DB. You can put the connecitn string in the web.config file or even do it in code using hte connectionstringbuilder.
you also need to make sure that your project includes the system.data.sqlclient library otherwise this won't work.
The entry in the web config file looks something like this.
<add name="ConString" connectionString="Data Source=localhost;Integrated Security=True;Initial Catalog="DBtouse";Persist Security Info=True;" providerName="System.Data.SqlClient"/>
or
<add key="ConString" value="Server=localhost;user=username;password=password;Initial Catalog=MyDBtouse;pooling=false"/>
the code behind loks like this:
Dim MyConnection As Data.SqlClient.SqlConnection
Dim Constring As New SqlClient.SqlConnectionStringBuilder
Constring.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings("ConString")
Constring.ConnectTimeout = 30
MyConnection.ConnectionString = Constring.ConnectionString
MyConnection.Open()
'Execute code here
MyConnection.Close()
MyConnection = Nothing