Microsoft SQL Server Management Studio Select Database Syntax Error [duplicate] - sql-server

It is a bit of a "chicken or egg" kind of query, but can someone dreamup a query that can return the name of the current database instance in which the query executes? Believe me when I say I understand the paradox: why do you need to know the name of the database instance if you're already connected to execute the query? Auditing in a multi-database environment.
I've looked at all the ## globals in Books Online. "SELECT ##servername" comes close, but I want the name of the database instance rather than the server.

SELECT DB_NAME()
Returns the database name.

SELECT
##servername AS 'Server Name' -- The database server's machine name
,##servicename AS 'Instance Name' -- e.g.: MSSQLSERVER
,DB_NAME() AS 'Database Name'
,HOST_NAME() AS 'Host Name' -- The database client's machine name

I'm not sure what you were exactly asking. As you are writing this procedure for an Auditing need I guess you're asking how do you get the current database name when the Stored Procedure exists in another database. e.g.
USE DATABASE1
GO
CREATE PROC spGetContext AS
SELECT DB_NAME()
GO
USE DATABASE2
GO
EXEC DATABASE1..spGetContext
/* RETURNS 'DATABASE1' not 'DATABASE2' */
This is the correct behaviour, but not always what you're looking for. To get round this you need to create the SP in the Master database and mark the procedure as a System Procedure. The method of doing this differs between SQL Server versions but here's the method for SQL Server 2005 (it is possible to do in 2000 with the master.dbo.sp_MS_upd_sysobj_category function).
USE MASTER
/* You must begin function name with sp_ */
CREATE FUNCTION sp_GetContext
AS
SELECT DB_NAME()
GO
EXEC sys.sp_MS_marksystemobject sp_GetContext
USE DATABASE2
/* Note - no need to reference master when calling SP */
EXEC sp_GetContext
/* RETURNS 'DATABASE2' */
Hope this is what you were looking for

You can use DB_NAME() :
SELECT DB_NAME()

SELECT DB_NAME() AS DatabaseName

simply use:
select ##servicename

You should be able to use:
SELECT SERVERPROPERTY ('InstanceName')

You can get the instance name of your current database as shown below:
SELECT ##SERVICENAME -- SQLEXPRESS
SELECT SERVERPROPERTY ('InstanceName') -- SQLEXPRESS

Related

How to find database name of any table

How to find the database name for a particular table when we have created a table and we forgot the database where we have created the same.
I have found the solution, we can simply find a database where we have created the table.
SELECT DISTINCT DB_NAME(database_id)
FROM [sys].[dm_db_index_operational_stats](NULL,NULL,NULL,NULL)
WHERE OBJECT_NAME(object_id,database_id) = 'tablename'
Try this EXEC sp_MSforeachdb
EXEC sp_MSforeachdb 'USE ? SELECT sc.TABLE_CATALOG, sc.TABLE_SCHEMA, sc.TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS sc WHERE TABLE_NAME=''YourTableName'''
if you are using SQL Server 2012 or more then simply you can find DataBase name using INFORMATION_SCHEMA like
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME ='your_table_name'
Here TABLE_CATALOG column shows DataBase Name.
There is no SQL Server ready solution to your problem.
To resolve it you need to loop through each database and to put the information schema into new table and then to query it.
Some idea can be found in the site bellow:
https://blog.sqlauthority.com/2008/04/29/sql-server-find-table-in-every-database-of-sql-server/

In SQL Server, how to find the database name when I know only a function name

I know only the function name. I don't know the database name where the function is been created and present.
I have around 30 databases so it takes more time to run the function on all the databases to find the database. is there any simple way to get the database name using only function name.
i'm using SQL server. Thanks in advance.
Surprisingly Jeroen's code didn't work on my SQL 2014 server. Try the following.
EXEC sp_msforeachdb
'if exists(select 1 from [?].sys.objects where name=''YourProcHere'')
select ''?'' as DbName from [?].sys.objects where name=''YourProcHere'''
Pretty sure this works as well:
sp_msforeachdb 'USE ? select ''?'' DBNAME where object_id(N''YOUR_FUNCTION'') is not null'
Thanks #Jeroen Mostert, Below SQL works for me:
sp_msforeachdb 'IF OBJECT_ID(''[?].dbo.myfunction'') IS NOT NULL SELECT ''?'''

Where did my new table go

I have a database called mbt. I wanted to write some data from temporary table to real table.
--I used this query.
SELECT * INTO new_table FROM #tmp
when i runned the query it returned normal message.
15813 row(s) affected
After that i checked my tables in mbt database, but i couldn't see 'new_table'
how could such a thing be, where the table might have gone.
I may have forgotten to use 'use MBT' statment at the beginning of the query. Does it make problem
I'm using ms sql server 2014(SP2)(KB3171021)-12.0.5000.0(X64)
ANSWER
It gone to Master DB
select 'master' as DatabaseName,
T.name collate database_default as TableName
from master.sys.tables as T
It Will create a new table on your database. but you did not use so it will store in master database on your server.
Run the query below to find databases which have the object new_table:
sp_MSForEachDB 'Use [?] IF EXISTS (SELECT 1 FROM sys.objects WHERE name= ''new_table'')
SELECT DB_NAME()'
I had the same problem. What i did is, I rewrite the statement of use Database and then refresh the database browser after that i got Result. You can try it. may be it will help you.
Always use command "USE db_name" to make sure that you are querying right database.
Below command will show all databases available on the server.
SHOW DATABASES;
If you are using GUI tool to connect DB server, there is a possibility that at the time of connection you got connected to different DB. If you executed the query to create table and inserted record. These records are inserted in new table in different DB than mbt.

How to determine the Server Name of a SQL Server with a T-SQL statement?

I want to know if there is a T-SQL statement that returns the Server name of a SQL Server.
This will give the actual physical machine name (e.g. in case of a cluster) as well as the server\instance name:
SELECT SERVERPROPERTY('ComputerNamePhysicalNetBIOS'), ##SERVERNAME;
One way is as follows:
SELECT ##SERVERNAME
Another way:
SELECT SERVERPROPERTY('ServerName')
SELECT ##servername
MSDN ##servername

Dynamically Specify Linked Server and DB Names in Stored Procedure

I have a query in a stored procedure that needs to be executed on different servers and databases according to some parameters.
How can I do this without using neither exec, nor sp_executesql?
I'm using SQL Server 2008.
Thank you.
UPDATE
I've found some links
http://www.eggheadcafe.com/software/aspnet/29397800/dynamically-specify-serve.aspx
http://www.sommarskog.se/dynamic_sql.html
Is using SYNONYM possible solution? If yes, than how?
UPDATE 2
I forgot to mention that all this servers are linked to the server where stored procedure is stored.
UPDATE 3
OPENROWSET or OPENDATASOURCE are not accessible either. I need a solution without building query string concating server name, schema name, db name.
It surely can be done by using if or case in stored procedure, but if we have 37 variations, then it's not a good solution.
Any other suggestions?
Nobody wants to answer, so I'll do it myself, just to have accepted answer.
There's isn't any way to do this. You need to use one of specified suggestions, anyway the query must be generating by concatenating.
Does OPENROWSET or OPENDATASOURCE help?
EDIT: If it works, you can change the database at runtime & execute the query using the present connection. I cannot see any other way of executing query the way you want.
What is wrong with running query using string i.e dynamic query?
/* DO THIS FOR EACH TABLE IN THE PROCEDURE*/
--BEGIN TABLE_1
DECLARE #LINKEDSERVER AS VARCHAR(50)
SET #LINKEDSERVER = DBO.FN_RETURN_SERVER('SBROUBLES')
DROP SYNONYM MYLINKEDSERVER
EXEC (' CREATE SYNONYM MYLINKEDSERVER FOR ' + #LINKEDSERVER + 'ANYDB.DBO.ANYTABLE')
--- END TABLE_1
-- UTILIZATION
SELECT COUNT(*) FROM MYLINKEDSERVER
--AND FN_RETURN_SERVER COULD BE ANY SELECT CASE ON SQL AS WELL

Resources