Unique ID of the SQL Server Database - sql-server

There are many SQL Server databases created from the same .BAK file.
I need to get the unique ID-value of each one. Getting UID of the DBfiles returns everywhere the same value.
Different situation with Oracle. It has a unique ID of each DB service.
Please, let me know what trick or method would be used in my case?
It should be just one SQL query.
Thanks.

This should do it:
Select * from Sys.Databases
In your case I think you need name, database_id and owner_sid columns, not sure if they're all relevant to your question.

I needed to get a unique database ID for product licensing reasons and eventually went with service_broker_guid. Eg
SELECT db.service_broker_guid FROM sys.databases db WHERE db.name = 'MyDatabase';
Result: ED2E8477-CDC3-49DF-ABEE-341B3E9277DF
NOTE: This value is usually 00000000-0000-0000-0000-000000000000 for databases where is_broker_enabled = 0. In our case, though, we just hunted for the first value that wasn't zeros:
SELECT TOP(1) service_broker_guid FROM sys.databases WHERE service_broker_guid <> '00000000-0000-0000-0000-000000000000' ORDER BY database_id;
I think you're fairly safe with that unless the database is moved or recreated but I haven't exhaustively tested that. (We'd just issue a new license key in the event of a customer issue.)

Related

SQL Server select from non-existent table

I have a query in classic asp where SQL statement is this:
Select * from active_Case
I verified in the DB connection it is using and found there is no such table / view. But a table does exist by the name of Cases. Internally it appears to be selecting from this table itself.
Actually this is somebody else's code. Thus I am not sure how is it possible. Is it really possible or am I missing something?
this will give you the base table name
select name, base_object_name
from sys.synonyms
where name = 'active_Case'
other than tables and view you can even check in User defined table type under types. or there might be chance your table is having a schema other than 'dbo.'

`Invalid object name` unless I specify database name in SQL Server 2008 queries

Up until today I've been able to run queries without using the [databaseName].[dbo].[fieldName] syntax. And all of a sudden, if I use select * from myTable I get an error for an invalid object. I can't possibly think of something that happened between shutting down my PC yesterday and today. Anyone know anything about this?
Msg 208, Level, 16, State 1 Line 1
Invalid object name 'mytable'
It's only been since today that I have to include the database name in the query. There are no other connections open and no other users of this instance of SQL Server.
I think you mean a query of the form select [fieldName] from [databaseName].[dbo].[mytable]
Here are some possible things to look out for:
Make sure that you are in the correct database context / catalogue (i.e. use [databasename], or select the correct database from the Available Databases drop down in SSMS)
Ensure that if you have a case sensitive collation on your database that the object names in your query match the exact case.
Check that the default schema for your user hasn't changed on this database. Although the default schema is usually [dbo], it can be changed.
Edit : More ideas:
Do SELECT DB_NAME() to see what the current database name is.
Check to see if someone has dropped the table or view entirely, e.g. from the target database, run:
Select * from sysobjects where name = 'myobject'
OR
Select * from sys.tables where name = 'mytable'
OR
Select * from INFORMATION_SCHEMA.TABLES

How to detect a SQL Server database's read-only status using T-SQL?

I need to know how to interrogate a Microsoft SQL Server, to see if a given database has been set to Read-Only or not.
Is that possible, using T-SQL?
The information is stored in sys.databases.
SELECT name, is_read_only
FROM sys.databases
WHERE name = 'MyDBNAme'
GO
--returns 1 in is_read_only when database is set to read-only mode.
Querying sys.databases for checking a DB's Read-Only property will only give the right information if the database has been explicitly set to Read-Only mode.
For databases that are in the passive servers (e.g. in AlwaysOn technology Secondary Servers), even though the databases cannot be written into, their Read-Only mode in sys.databases would still be set as False(0).
Hence, it is advisable to check the Read-Only mode of databases using the statement:
SELECT DATABASEPROPERTYEX('MyDBNAme', 'Updateability');
I was trying to use the p.campbell's answer to check if my Azure SQL DB is the primary one or the read only replica - it didn't work. Both the primary DB and the replica returned had 0 on the is_read_only field.
Here's what worked for me:
SELECT DATABASEPROPERTYEX('MyDBNAme', 'Updateability');
the above select statement returns string 'READ_ONLY' or 'READ_WRITE'.
Here is a command to display or set this property.
EXEC sp_dboption "AdventureWorks", "read only"
Sample output
OptionName CurrentSetting
read only OFF
If DB is part of your Always On and the secondary node is designed in Read_Only then
"sys.databases --> Is_Read_Only" column wont show the correct result ! its a bug that Microsoft needs to address it during the next versions.
If you would like to check all DB statuses in your server, use this:
SELECT name, user_access_desc, is_read_only, state_desc, recovery_model_desc
FROM sys.databases;
You can quickly determine your next steps.

What is the sql to query SqlServer system databases to find an DB object?

I have a large db with many tables and sprocs, and I want to find and see, for example, if there is a table with a name that has "setting" as part of it. I'm not very familiar with SqlServer's System Databases like master, msdb etc., I know there is a way to query one of those dbs to get what I need back, does someone know how to do it?
Thank you,
Ray.
SQL Server also supports the standard information schema views. Probably better to use them, since this query should also work across different database engines if you ever need to do a migration:
SELECT * FROM INFORMATION_SCHEMA.tables where table_name LIKE '%Settings%'
the table you want is sys.objects
SELECT *
FROM sys.objects
The table with the info you seek is called sysobjects. Here's a query for what you describe:
SELECT * FROM sysobjects WHERE xtype = 'U' AND NAME LIKE '%setting%'
(U is the type for user tables)
For Sql Server 2005
SELECT * FROM sys.objects where type in ('U') and name like '%setting%'

How can I get a list of all of the user databases via t-sql?

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';

Resources