Script to get detached databases from folder and subfolders - sql

Is there a way to find out if SQL Server databases are attached from a directory with many subfolders apart from going to properties of each .mdf and checking if it is attached?
Is there a script that can check folders/subfolders an write to file to accomplish this?
THanks all.

This should be fairly easy to do:
firstly i would query the database server sysdatabase table to locate all databases you have attached and there corresponding file names and store in a temporary table.
Using the xp_cmdshell function exec a dos DIR command to list all MDF/LDF files with the right switch to navigate folders and store the results in another temporary table
Compare these tables and you will be able to find what files are not attached.
I have done similar tasks before and used both SSIS and Direct Transact-SQL
T

When you need to read the file system from T-SQL, I find that CLRs have the most flexibility. They give you full access to the system.io namespace as well as support for table valued functions.
Have a look at the SQL Server CLR IO Utility. There is a full solution here which enables filesystem functionality that is not easily available with the frowned upon xp_cmdshell.
The table valued function, SQLIO_fnGetFiles, can be used to join to the sys.master_files table and return files which are no longer attached to a database. In this example, the CLR is deployed to a database named CLRS:
USE master
SELECT fs.PATH FileSystemPath
, FileIsAttached = CASE WHEN d.name IS NULL THEN 'YES' ELSE 'NO' END
, d.name DatabaseName
, mf.name FileLogicalName
, mf.physical_name DatabaseFilePath
, FileType = CASE mf.type_desc WHEN 'ROWS' THEN 'DATA' ELSE mf.type_desc END
FROM CLRS.dbo.SQLIO_fnGetFiles('L:\MSSQL\','*df',1) fs
LEFT OUTER JOIN sys.master_files mf ON fs.PATH = mf.physical_name
LEFT OUTER JOIN sys.databases d ON d.database_id = mf.database_id
There are also other methods (powershell, .net, ssis,...) to accomplish this. My experience is that once you deploy the IO Utility solution, you'll find many other time saving uses for it.

Related

SSMS - get DDL of all views in a schema

I have a SQL Server database with several schemas, each of them contains several views.
I need to create the same views in other databases so I would like to get the DDL of all the views in a script, generated through SQL.
In Oracle it was quite easy, accessing ALL_VIEWS and referencing the QUERY column.
How can i do the same in SQL Server?
Thanks
EDIT
I know I can right click and get the script of an object in SSMS, I need to do this for 20/30 views, and don't want to do it manually
I'm trying to avoid as much as possible to do manual work. I want to have a query which generates the scripts for all objects in one or more schemas.
This is because the schemas are evolving quickly, with new views being created. I need to reproduce them in several other databases and I'm trying to have a solid procedure for deploying
With the Views node highlighted in Object Explorer, open Object Explorer Details (F8 or Shift+F8 if I recall correctly).
This will open a window with all the views in a list, and you highlight the views you want and right-click > script. Here you can sort by name, filter by schema (probably what you mean by "owner"), etc.
I'm not sure how you can possibly select 20 or 30 views in any scenario without introducing the possibility of human error.
You can write a script that does something similar, with Results to Text, e.g.
SET NOCOUNT ON;
SELECT 'GO' + OBJECT_DEFINITION(object_id)
FROM sys.views
WHERE schema_id = SCHEMA_ID(N'schema_name');
The problem is Management Studio has crippling limits to text output, even after customizing Tools > Options > Query Results > SQL Server > Results to Text and setting that to the max (8,192). So if any of your views are longer than 8,192 characters, you'll need to work around that somehow.
But really, Larnu is right. Your views should be in source control, and that should be your source for deployment, not some manual extraction from the database.
If you want to get the view definitions from a query, you can use sql_modules.
select m.definition
from sys.sql_modules m
join sys.objects o on o.object_id = m.object_id
join sys.schemas s on s.schema_id = o.schema_id
where o.type = 'V'
and s.name in ('your', 'schemas', 'here')
Customize as desired to select the views you want.
You can get views, schemas and definitions by quite standard way:
select * from information_schema.views

How to get table's metadata from linked server (SQL Server)

How to get tables metadata from linked server/another database? The query below works ideally when running on the main server, but returns null if calls remote server or even another database.
select object_name(major_id)
from server.bd1.sys.extended_properties
Probably, it is caused that the specific path for metadata functions (like object_name()) is not defined. Hence, functions take data not from remote server/DB, but server and DB they are launched.
If it is true, would you prompt the specific path (DB, schema) of metadata functions that I could define path explicitly.
Thank you for help.
Solved by using direct query to the tables with metadata except using builtin functions
select
c.name schma
,a.name tble
,b.name desc_categ
,b.value desc_name
from server.db.sys.objects a
join server.db.sys.extended_properties b on a.parent_object_id = b.major_id
join server.db.sys.schemas c on a.schema_id = c.schema_id

What is the best way to find DML references to objects in SQL Server?

Something I have always struggled with is finding DML references to tables in SQL server at the company I work. We have our code held in TFS source control and deployed to a shared development environment so I can search using either file searching or t-sql code. The challenge I have is that I can easily find all references to a table name but I can't find a good way to filter further to a particular statement like UPDATE/INSERT/MERGE.
A large challenge in this is that the company I work at has a lot of dynamic SQL so I think the best method will be some form of text searching. The other challenge is that coding is written as each developer sees fit so an UPDATE statement will not be written in any 'standard' way throughout the code base - i.e. the table name could be on the same line as the DML statement or on a separate line.
I have been able to use some basic regular expression searching in Visual Studio to find instances where the keyword is on the same line as the table name but I don't know how to search for it being 'close'.
Has anybody else faced this issue and found a good way to search for this information? What I would love is a tool where you put in a t-sql reserved keyword and an object name and the tool shows you all references.
One way to at least see all the code across Views, SP, Functions, etc is to run this:
--will show you all source code from procs, views, functions etc
select *
from syscomments
--or better to join it on sysobjects and display only view source code for example
select o.id,o.name,c.text
from syscomments c
inner join sysobjects o on o.id = c.id
where o.[Type] = 'V'
I found once I have all of this, I can then do easy searching in Excel or via Notepad++.
I hope that helped.

Stored procedure dependencies in SQL Server Management Studio

I don't know much about the MS world, but now it happens to be that I have to use SQL Server Management Studio 2008.
My problem: I have a column in a table, and I need to see all the stored procedures that may be acting on it.
I tried right-clicking and going 'View Dependencies' but that doesn't seem to be returning everything that it should be.
Questions like this one: SQL Server Dependencies have answers that offer 3 types of solutions
Paid third party tools.
Writing your own scripts.
Exporting everything into text files and grepping them.
WTF? Am I missing something obvious? Is that actually how things work? I would imagine that this is a very common use case: you want to alter table and you want to make sure you won't break anything. Or if say you're looking at a new project with a DB for the first time and you want to see how certain columns get populated with stored procedures. Is there actually no quick and easy built-in workflow to do this?
If you need to find database objects (e.g. tables, columns, triggers) by name - have a look at the FREE Red-Gate tool called SQL Search which does this - it searches your entire database for any kind of string(s).
It's a great must-have tool for any DBA or database developer - did I already mention it's absolutely FREE to use for any kind of use??
Use this query:
SELECT ROUTINE_NAME, ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%YOUR COLUMN %'
AND ROUTINE_TYPE='PROCEDURE'
I have spent a good amount of time trying to find a way to identify column level dependencies in a quick way without having to search text or use third party applications. The other challenge is finding dependencies across multiple databases where table names may repeat, which will cause false positives when searching SP text.
As of SQL 2008, there is a function that returns dependencies across databases on a field level.
The code below works with a few exceptions:
It will fail if there are stored procedures with invalid references on tables/fields that have been deleted (Incidently I found this to be useful to find SPs that had been accidentally broken by table modifications).
It doesn't find all dependencies in cases where the SP is using temp tables in unusual ways.
In some cases I found that it was returning false positives for complex stored procedures.
MSDN Documentation
This code should be run from within the database where the SP is in order to be able to cross to other database dependencies.
SELECT
--SP, View, or Function
ReferencingName = o.name,
ReferencingType = o.type_desc,
--Referenced Field
ref.referenced_database_name, --will be null if the DB is not explicitly called out
ref.referenced_schema_name, --will be null or blank if the DB is not explicitly called out
ref.referenced_entity_name,
ref.referenced_minor_name
FROM sys.objects AS o
cross apply sys.dm_sql_referenced_entities('dbo.' + o.name, 'Object') ref
where o.type in ('FN','IF','V','P','TF')
I wonder why you cannot see the dependencies via the 'View Dependencies' dialog because it works perfectly fine for me. Nevertheless you can query the 'sys.sql_expression_dependencies' system view and obtain the dependency information that you want.
Example
SELECT OBJECT_NAME(referencing_id),OBJECT_NAME(referenced_id)
FROM sys.sql_expression_dependencies
WHERE referenced_id = OBJECT_ID('XXX')
You can of course project other information that you might need.
List of All Dependent Objects in single query.
select distinct A.name from sys.procedures A inner join sys.sql_dependencies B
on A.object_id = B.object_id;
OR
select distinct A.name from sys.objects A inner join sys.sql_dependencies B
on A.object_id = B.object_id where A.type_desc = 'mentioned your Object Type';

SSMS: How to view a stored procedure/view/function without scripting?

i want to look at the definition of a stored procedure, view, or user-defined function.
In SQL Server Management Studio 2005 the only way i've found to do this is:
Right-click
Script stored procedure as
ALTER To
New Query Editor Window
goto 1
i don't want to script it, i want to look at it.
My task today in SSMS is to quickly go through the stored procedures to find one i'm interested in. i've loaded up Enterprise Manager in Windows XP mode (MMC snap-in doesn't run nativly in 64-bit), and my job is much easier:
Push enter
goto 1
i'm trying to find the way to look at a stored procedure - i'm not interested in scripting it.
I did some quick google searches and found this.
Copy and Paste from website:
-- Get Stored Procedure Content
-- Name = Stored Procedure Name.
-- Colid = Multiple lines, their sequence.
SELECT text
FROM syscomments
WHERE id = (SELECT id FROM sysobjects WHERE name = '{0}')
ORDER BY colid
Depending on where the information is, have you tried to filter them "to find one I'm interested in"?
SELECT text
FROM syscomments c
INNER JOIN sysobjects o
ON o.id = c.id
WHERE o.type = 'P'
and o.Name = '{0}'
FOR XML PATH('')
exec sp_helptext N'<stored proc name>'
Example:
exec sp_helptext N'mydatabase.dbo.myStoredProc'
This will shows all the lines of the procedure without having to maneuver the GUI to the sp.
Using syscomments has potential problem: big procedures are splitted in several rows and sometimes important identifiers are divided into 2 parts. Like:
row1: .....veryimportantide
row2: ntifier.....
so, if you are looking for veryimportantidentifier - you will never find it. (for example - looking for all references of it)
When I look for something and it is very important - I generate scripts of all objects and navigate there using something like Notepad++ or Visual Studio
I found a solution for preview the stored function in SQL Server Management Studio 2012. It is non-programmer solution :)
Find chosen function in Object Explorer.
Click on it right mouse button.
Choose Modify.
Function preview is displayed. You can copy it to NotePad ++ and analyse.
I hope this will be helpful.