Get list of SQL server databases which files have been deleted - sql

My goal is getting list of SQL server databases which files have been deleted.
In other words. I attach a db from mount, then close the mount so actually I have the attached db without files.
At first it seemed to be easy. Just pretty easy select:
SELECT
'DB_NAME' = db.name,
'FILE_NAME' = mf.name,
'FILE_TYPE' = mf.type_desc,
'FILE_PATH' = mf.physical_name
FROM
sys.databases db
INNER JOIN sys.master_files mf
ON db.database_id = mf.database_id
WHERE
--and specific condition here
But it turned out differently. Sql server has almost the same information about a regular database and a database which doesn't have files. So I had to try something else.
Further I tried to use state of database. And it was quite strange.
Unfortunately the following query gives me wrong(or not actual information):
SELECT state
FROM sys.databases
WHERE name = N'TestDB'
state
-----
0
And 0 means ONLINE according to this link
But actually the database has RECOVERY_PENDING state. It looks like that sql server information about my TestDB us out of date and should be refreshed. But I have no idea how to achieve this. But after executing any of following query this info(db state) is being refreshed:
EXEC sp_helpdb N'TestDB'
ALTER DATABASE N'TestDB' SET SINGLE_USER WITH ROLLBACK IMMEDIATE
USE N'TestDB'
--etc
--all requests are terminated with the same error
Msg 5120, Level 16, State 101, Line 10
Unable to open the physical file "C:\MOUNT\b4c059e8-3ba6-425f-9a2a-f1713e7719ca\TestDB.mdf". Operating system error 3: "3(The system cannot find the path specified.)".
File activation failure. The physical file name "C:\MOUNT\b4c059e8-3ba6-425f-9a2a-f1713e7719ca\TestDB_log.ldf" may be incorrect.
File activation failure. The physical file name "C:\MOUNT\b4c059e8-3ba6-425f-9a2a-f1713e7719ca\TestDB_log-2.ldf" may be incorrect.
Msg 5181, Level 16, State 5, Line 10
Could not restart database "TestDB". Reverting to the previous status.
Msg 5069, Level 16, State 1, Line 10
ALTER DATABASE statement failed.
So do you have any idea ?
And also I've asked the question looks like this here differently.

Finally, I've found what i actually need.
I can chech whether the specific file exists or not by sql server:
CREATE FUNCTION dbo.fn_FileExists(#path varchar(512))
RETURNS BIT
AS
BEGIN
DECLARE #result INT
EXEC master.dbo.xp_fileexist #path, #result OUTPUT
RETURN cast(#result as bit)
END;
GO
So i just need to execute the function above for each file which i can get by executing for example following query:
SELECT
DISTINCT 'FILE_PATH' = physical_name
FROM sys.master_files

Related

Insert return records from stored procedure - SQL

The script below return a select records:
EXEC [LINK_SERV].[DB_SAMPLE].[dbo].[SP_SAMPLE] '1235123'
The I want to insert the return records to a temp table so I wrote the script below (assumed temp table is already created):
INSERT INTO #TempTable
EXEC [LINK_SERV].[DB_SAMPLE].[dbo].[SP_SAMPLE] '1235123'
But I get this error:
OLE DB provider "SQLNCLI11" for linked server "LINK_SERV" returned message "The partner transaction manager has disabled its support for remote/network transactions.
Msg 7391, Level 16, State 2, Line 25
The operation could not be performed because OLE DB provider "SQLNCLI11" for linked server "LINK_SERV" was unable to begin a distributed transaction.
Please advise the specific config to enable this. I tried the same code in some other server and it work. Thank you in advance.
This is where the beauty of OPENQUERY() comes into great use.
i.e. something like this...
INSERT INTO dbo.MyTable2
SELECT Col1, Col2, etc
FROM dbo.MyTable1
LEFT JOIN OPENQUERY(<<LINKEDSERVER>>,
'SELECT BLAHBLAH
FROM dbo.BLAHBLAH WHERE <something> = <something>);

SQL Server could not find stored procedure 'show'

I can't use the most basic procedure, show, as it throws an error:
Msg 2812, Level 16, State 62, Line 1
Could not find stored procedure 'show'.
I used:
SHOW DATABASES
Please help me find answers to this issue.
To list all Databases in SQL Server,
Select * from sys.databases
To exclude in-built DBs,
Select * from sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');
Try to refresh local Cache which is under the Intellisense.

Early execution of "sp_rename" causes query to fail

I'm having a strange problem with an MSSQL Query that I'm trying to run in Microsoft SQL Server 2014. It is an update script for my database structure. It should basically rename a Column (from Price to SellingPrice) of a Table after its content was merged to another one.
USE db_meta
GO
DECLARE #BakItemPrices TABLE
(
ItemNum int,
Price int,
CashPrice int
)
-- backup old prices
insert into #BakItemPrices
select ItemNum, Price from dbo.ItemInfo
-- merge into other table
alter table ShopInfo
add column Price int NOT NULL DEFAULT ((0))
update ShopInfo
set ShopInfo.Price = i.Price
from ShopInfo s
inner join #BakItemPrices i
on s.ItemNum = i.ItemNum
GO
-- rename the column
exec sp_rename 'ItemInfo.Price', 'SellingPrice', 'COLUMN' -- The Debugger executes this first
GO
This query always gave me the error
Msg 207, Level 16, State 1, Line 13
Invalid column name 'Price'.
I couldn't understand this error until I debugged the query. I was amazed as I saw that the debugger wont even hit the breakpoint I placed at the backup code and says that "its unreachable because another batch is being executed at the moment".
Looking further down I saw that the debugger instantly starts with the exec sp_rename ... line before it executes the query code that I wrote above. So at the point my backup code is being executed the Column is named SellingPrice and not Price which obviously causes it to fail.
I thought queries get processed from top to bottom? Why is the execute sequence being executed before the code that I wrote above?
Script is sequenced from top to down. But some changes to schema is "visible" after the transaction with script is committed. Split your script into two scripts, it can help.

Running scripts - Check if a SQL Server 2008 database exists and replace if not (USE Database)

Running scripts - check if a SQL Server 2008 database exists and replace if not (USE Database)
I run a script on lots of servers. However some database names are not always the same hence we have to edit 'use database'
if DB_ID('sports') is not null -- check to see if exists
use sports
else
use SportsLive`-- use the correct one
Always one is not going to exist...
Msg 911, Level 16, State 1, Line 15
Database 'SportsLive' does not exist. Make sure that the name is entered correctly.
Any way around this?
use[xxx] must be at beginning of the code so
if you what to use this query
you need to put the rest of the code together
with the 'use[xxx]...' like in the example
DECLARE #i nvarchar(50)
DECLARE #a nvarchar(50)
SET #i =DB_NAME(coalesce((db_id('sports')),(db_id('SportsLive'))))
SELECT #i
SET #a= 'USE ['+#i+']
select * from [your table]'
EXEC (#a)

How - create and use database directly after creation in SQL Server?

I created a sql script to check if a database already exist, if it already exists it deletes and re-creates.
After I would like to connect it directly after its creation for creating tables ..
Here is my code but it does not work.
He announces an error message
Msg 911, Level 16, State 1, Line 10
Database 'Arms2' does not exist. Make sure that the name is entered correctly.
My script
IF EXISTS (select * from sys.databases where name = 'Arms2')
BEGIN
DROP DATABASE Arms2
PRINT 'DROP DATABASE Arms2'
END
CREATE DATABASE Arms2;
PRINT 'CREATE DATABASE Arms2'
USE Arms2
CREATE TABLE .....
Put a GO statement after the CREATE...
...
CREATE DATABASE Arms2;
PRINT 'CREATE DATABASE Arms2'
GO
USE Arms2