How can I get the list of available databases on a SQL Server instance? I'm planning to make a list of them in a combo box in VB.NET.
Execute:
SELECT name FROM master.sys.databases
This the preferred approach now, rather than dbo.sysdatabases, which has been deprecated for some time.
Execute this query:
SELECT name FROM master.dbo.sysdatabases
or if you prefer
EXEC sp_databases
in light of the ambiguity as to the number of non-user databases, you should probably add:
WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');
and add the names of the reporting services databases
To exclude system databases:
SELECT [name]
FROM master.dbo.sysdatabases
WHERE dbid > 6
Edited : 2:36 PM 2/5/2013
Updated with accurate database_id, It should be greater than 4, to skip listing
system databases which are having database id between 1 and 4.
SELECT *
FROM sys.databases d
WHERE d.database_id > 4
SELECT [name]
FROM master.dbo.sysdatabases
WHERE dbid > 4
Works on our SQL Server 2008
Use the query below to get all the databases:
select * from sys.databases
If you need only the user-defined databases;
select * from sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');
Some of the system database names are (resource,distribution,reportservice,reportservicetempdb) just insert it into the query if you have the above db's in your machine as default.
Since you are using .NET you can use the SQL Server Management Objects
Dim server As New Microsoft.SqlServer.Management.Smo.Server("localhost")
For Each db As Database In server.Databases
Console.WriteLine(db.Name)
Next
SELECT [name]
FROM master.dbo.sysdatabases
WHERE dbid > 4 and [name] <> 'ReportServer' and [name] <> 'ReportServerTempDB'
This will work for both condition, Whether reporting is enabled or not
I use the following SQL Server Management Objects code to get a list of databases that aren't system databases and aren't snapshots.
using Microsoft.SqlServer.Management.Smo;
public static string[] GetDatabaseNames( string serverName )
{
var server = new Server( serverName );
return ( from Database database in server.Databases
where !database.IsSystemObject && !database.IsDatabaseSnapshot
select database.Name
).ToArray();
}
If you want to omit system databases and ReportServer tables (if installed)
select DATABASE_NAME = db_name(s_mf.database_id)
from sys.master_files s_mf
where
s_mf.state = 0 -- ONLINE
and has_dbaccess(db_name(s_mf.database_id)) = 1
and db_name(s_mf.database_id) NOT IN ('master', 'tempdb', 'model', 'msdb')
and db_name(s_mf.database_id) not like 'ReportServer%'
group by s_mf.database_id
order by 1;
This works on SQL Server 2008/2012/2014. Most of query comes from "sp_databases" system stored procedure. I only removed unneeded column and added where conditions.
Not sure if this will omit the Report server databases since I am not running one, but from what I have seen, I can omit system user owned databases with this SQL:
SELECT db.[name] as dbname
FROM [master].[sys].[databases] db
LEFT OUTER JOIN [master].[sys].[sysusers] su on su.sid = db.owner_sid
WHERE su.sid is null
order by db.[name]
In SQL Server 7, dbid 1 thru 4 are the system dbs.
perhaps I'm a dodo!
show databases; worked for me.
If you are looking for a command to list databases in MYSQL, then just use the below command. After login to sql server,
show databases;
To exclude system databases :
SELECT name FROM master.dbo.sysdatabases where sid <>0x01
Related
How do I select current database name and all the schema for the database name in SYBASE ASE using a query
tried Select db_name
gives invalid column name
Current database:
select db_name()
By 'schema' I'm assuming you mean a user (in the database) who owns at least one object:
select distinct(user_name(uid)) from sysobjects
NOTE: I'm not sitting in front of an ASE instance at the moment so can't recall, or verify, if the 2nd query could generate a NULL ... should be easy enough to test and add an optional where clause to filter out as needed
I know about getting the database names by doing the following:
select *
from master..sysdatabases
order by Name
What I want to be able to do is return all the files related to each database on the server. To get the list of files per database I have to do something similar to the following:
use [database]
select *
from sysfiles
Unfortunately I need the use prefix as sysfiles only pulls from the database I'm using.
Ideally I want to be able to wrap this into a view that can be called and hooked into zabbix via an odbc database monitoring item.
Let's say I have 3 database:
DB1
DB2
DB3
I want a view that will show
Database Name FileName
--------------------------------
DB1 c:\mnt\db1.mdf
DB1 c:\mnt\db1.ldf
DB2 c:\mnt\db2.mdf
DB2 c:\mnt\db2.ldf
DB3 d:\mnt\db3.mdf
DB3 d:\mnt\db3.ldf
You can query it using the sys.databases and sys.master_files views:
SELECT
db.name,
FileName = mf.name,
PhysicalFileName = mf.physical_name,
Type = mf.type_desc
FROM sys.databases db
INNER JOIN sys.master_files mf
ON mf.database_id = db.database_id
WHERE db.name NOT IN('msdb', 'master', 'tempdb', 'model')
ORDER BY db.name
I am going to get the list of all users, including Windows users and 'sa', who have access to a particular database in MS SQL Server.
Basically, I would like the list to look like as what is shown in SQL Server Management Studio (i.e. the list that is shown when you expand [databse] -> Security -> Users) with one important exception: I do not want to see the 'dbo' in the list. Rather, I would like to see the actual user who owns the database. So, for example, if 'sa' is the 'dbo', 'sa' must be included in the list instead of 'dbo'. Another note not to be missed is, the list in the SQL Server Management Studio normally shows Windows users in addition to SQL users, And I would like those users to be included as well.
So far, I have been able to come up with the following query:
SELECT * FROM sys.database_principals where (type='S' or type = 'U')
This query is almost right but the problem is it doesn't satisfy the 'dbo' condition.
How can I change this query or should I use another one?
For the SQL Server Owner, you should be able to use:
select suser_sname(owner_sid) as 'Owner', state_desc, *
from sys.databases
For a list of SQL Users:
select * from master.sys.server_principals
Ref.
SQL Server Tip: How to find the owner of a database through T-SQL
How do you test for the existence of a user in SQL Server?
EXEC sp_helpuser
or
SELECT * FROM sysusers
Both of these select all the users of the current database (not the server).
Whenever you 'see' something in the GUI (SSMS) and you're like "that's what I need", you can always run Sql Profiler to fish for the query that was used.
Run Sql Profiler. Attach it to your database of course.
Then right click in the GUI (in SSMS) and click "Refresh".
And then go see what Profiler "catches".
I got the below when I was in MyDatabase / Security / Users and clicked "refresh" on the "Users".
Again, I didn't come up with the WHERE clause and the LEFT OUTER JOIN, it was a part of the SSMS query. And this query is something that somebody at Microsoft has written (you know, the peeps who know the product inside and out, aka, the experts), so they are familiar with all the weird "flags" in the database.
But the SSMS/GUI -> Sql Profiler tricks works in many scenarios.
SELECT
u.name AS [Name],
'Server[#Name=' + quotename(CAST(
serverproperty(N'Servername')
AS sysname),'''') + ']' + '/Database[#Name=' + quotename(db_name(),'''') + ']' + '/User[#Name=' + quotename(u.name,'''') + ']' AS [Urn],
u.create_date AS [CreateDate],
u.principal_id AS [ID],
CAST(CASE dp.state WHEN N'G' THEN 1 WHEN 'W' THEN 1 ELSE 0 END AS bit) AS [HasDBAccess]
FROM
sys.database_principals AS u
LEFT OUTER JOIN sys.database_permissions AS dp ON dp.grantee_principal_id = u.principal_id and dp.type = 'CO'
WHERE
(u.type in ('U', 'S', 'G', 'C', 'K' ,'E', 'X'))
ORDER BY
[Name] ASC
SELECT name FROM sys.database_principals WHERE
type_desc = 'SQL_USER' AND default_schema_name = 'dbo'
This selects all the users in the SQL server that the administrator created!
Go for this:
SELECT name,type_desc FROM sys.sql_logins
I try to avoid using the "SELECT * " option and just pull what data I want or need.
The code below is what I use, you may cull out or add columns and aliases per your needs.
I also us "IIF" (instant if) to replace binary 0 or 1 with a yes or no. It just makes it easier to read for the non-techie that may want this info.
Here is what I use:
SELECT
name AS 'User'
, PRINCIPAL_ID
, type AS 'User Type'
, type_desc AS 'Login Type'
, CAST(create_date AS DATE) AS 'Date Created'
, default_database_name AS 'Database Name'
, IIF(is_fixed_role LIKE 0, 'No', 'Yes') AS 'Is Active'
FROM master.sys.server_principals
WHERE type LIKE 's' OR type LIKE 'u'
ORDER BY [User], [Database Name];
GO
Hope this helps.
To run a query returning users of individual databases, try this:
EXEC sp_MSforeachdb 'USE ? <QUERY HERE>'
This will run a query (and return a result) for each database. So to get all users (probably with a lot of internal users and roles you are not interested in, try:
EXEC sp_MSforeachdb 'USE ?; SELECT DB_NAME(), * FROM sys.database_principals;'
Just apply filters mentioned in other replys to get exactly the subset you are looking for.
I'm using some modifications to Glenn Berry's excellent DMV queries!
However, I would like to add to the resultset the 'last server restart', or to be more specific, the date/time the statistics for (all, the specific) DMV was reset.
Since it would be quite important to know last reset when looking at the statistics, I want to make absolutely sure the date/time is accurate and shown.
Question: How can you get the most accurate date/time of when a/all DMV statistic was reset?
Thanks!
-D
SELECT sqlserver_start_time FROM sys.dm_os_sys_info
Using a prior question (different key words), I ended up using this approach. As always, up to the individual what would be 'best' for them!
SELECT create_date
FROM sys.databases
WHERE name = 'tempdb'
source: Find out how long the sql server service has been running, from t-sql
This will work but you have to know the service name also its only available with R2 and later
SELECT last_startup_time
FROM sys.dm_server_services
WHERE servicename = "Your Service name"
Although this won't be totally accurate since you can also reset the DB specific views via a DB detach or a DB close.
Also there are two views that can be reset on a live db sys.dm_os_latch_stats and sys.dm_os_wait_stats
There are many ways to check when was SQL server restarted last time.
Below mentioned SQL queries can be used to quickly find out the
server restart date time.
SELECT sqlserver_start_time FROM sys.dm_os_sys_info;
SELECT login_time FROM sys.dm_exec_sessions WHERE session_id = 1;
select start_time from sys.traces where is_default = 1 ;
SELECT crdate FROM sysdatabases WHERE name='tempdb' ;
SELECT create_date FROM sys.databases WHERE name = 'tempdb' ;
There are various way to find out SQL Server reboot time. Following are the codes which return the server re-boot date:
SELECT sqlserver_start_time FROM sys.dm_os_sys_info;
SELECT login_time FROM sys.dm_exec_sessions WHERE session_id = 1;
SELECT start_time from sys.traces where is_default = 1;
SELECT crdate FROM sysdatabases WHERE name='tempdb';
SELECT create_date FROM sys.databases WHERE name = 'tempdb';
I want to get a list of all of the user databases from an mssql server instance. What's the best way to do this?
I know I can select from sys.databases, but I don't see any way to filter out system databases besides hardcoding a list of names to exclude.
I need the script to work on 2000/2005 and 2008.
If the approach I listed above is the only way to go, what are list of names I should exclude? I don't know if 2005 or 2008 added any new system databases off the top of my head.
Was looking in to this again today and decided to profile what Management Studio was doing to populate the Object Explorer details.
Turns out the solution Microsoft have implemented is pretty simplistic and boils down to the following:
SELECT *
FROM master.sys.databases
WHERE Cast(CASE WHEN name IN ('master', 'model', 'msdb', 'tempdb') THEN 1 ELSE is_distributor END As bit) = 0
Please note that this was performed using SSMS 2008R2 (10.50.4033.0).
The first query will return a table with data regarding all of the databases on the instance:
Select *
From sys.databases
From this table you'll notice you can narrow down the scope of data you're looking for by using the WHERE clause. For example, the following queries will essentially return the same result table (the one you're most likely looking for):
Select *
From sys.databases
Where database_id > 5
Select *
From sys.databases
Where len(owner_sid)>1
These queries will work in SQL Server 2008 and 2012.
On SQL Server 2008 R2 Express, looks like I cannot reliably use any of the above methods. INFORMATION_SCHEMA.SCHEMATA only shows me information in the current database, db_id (database_id) #5 is my first user database, and owner_sid on two of my user databases on one of my mirrored databases (running on SQL Server 2008 R2 Standard) shows owner_sid = 1 for my two most recently created databases. (PablolnNZ's comment above is correct: I did not set an explicit owner for those two databases so it still shows as having an owner of 'sa'.)
The only reliable means I was able to use was the following:
SELECT name FROM sys.databases
WHERE name NOT IN ('master', 'model', 'tempdb', 'msdb', 'Resource')
This works in 2005, not 100% sure about the other versions but I think it will fly. It's a bit of a hack but might get you what you need:
select * from sys.databases where len(owner_sid)>1
As nasty as it sounds to hardcode things. The names and number of system databases has been fairly consistent for several versions of SQL. However, if that is too unpleasant you could semi-hardcode them into a table and then plug that into your query.
Not sure if you can offhand. One note -- on 2k you'll have to use master.dbo.sysdatabases and not master.sys.databases (which doesn't exist in 2k).
Starting with SQL Server 2008 you have access to a view called sys.databases which when joined with sys.server_principals can eliminate the databases owned by sa, which you can (most often) safely discern are the "system databases". Thus, allowing you to filter these items out.
select
d.name
,d.database_id
from
sys.databases d
join
sys.server_principals p
on p.sid = d.owner_sid
where
p.name <> 'sa';