>Ti ringrazio! Fai pure con comodo, tanto leggerò domattina!
Allora, eccoci qua
SQL Server 2000 offre la possibilità di leggere i metadati senza la necessità di accedere alle tabelle di sistema ricorrendo alle Information Schema Views.
Le Information Schema Views aderiscono allo standard ANSI SQL-92 e permettono alle applicazioni di funzionare correttamente anche nel caso in cui le tabelle di sistema subiscano notevoli modifiche (per esempio dovute all'installazione di un service pack).
Per recuperare la lista di tutti i database a cui può accedere l'utente connesso, puoi ricorrere all'Information Schema View SCHEMATA:
USE Northwind;
GO
SELECT CATALOG_NAME
FROM INFORMATION_SCHEMA.SCHEMATA;
GO
/* Output:
CATALOG_NAME
-------------
master
tempdb
model
msdb
pubs
Northwind
lumigent
(7 row(s) affected)
*/
Per recuperare l'elenco delle tabelle a cui può accedere l'utente connesso, puoi utilizzare l'Information Schema View TABLES:
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE';
GO
/* Output:
TABLE_NAME
---------------------
Categories
CustomerCustomerDemo
CustomerDemographics
Customers
dtproperties
Employees
EmployeeTerritories
Order Details
Orders
Products
Region
Shippers
Suppliers
Territories
TestMoney
(15 row(s) affected)
*/
Ovviamente dovrai looppare tra tutti i database per recupera l'elenco di tutte le tabelle. Questa operazione può essere svolta manualmente utilizzando il comando USE <nome database> oppure puoi sfruttare la stored procedure non documentata sp_MSforeachdb per interrogare tutti i database:
EXEC dbo.sp_MSforeachdb '
USE ?;
SELECT DB_NAME() AS [Database], TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = ''BASE TABLE'';
';
GO
/* Output:
Database TABLE_NAME
---------- --------------------------------------
lumigent leAuditCollectAlerts
lumigent leAuditCollectConfigVars
lumigent leAuditCollectDatabases
lumigent leAuditCollectEventData
lumigent leAuditCollectNotification
Database TABLE_NAME
---------- --------------------------------------
master ArBoxRighe
master MSreplication_options
master spt_datatype_info
master spt_datatype_info_ext
master spt_fallback_db
master spt_fallback_dev
master spt_fallback_usg
master spt_monitor
master spt_provider_types
master spt_server_info
master spt_values
Database TABLE_NAME
---------- --------------------------------------
Database TABLE_NAME
---------- --------------------------------------
msdb backupfile
msdb backupmediafamily
msdb backupmediaset
msdb backupset
msdb log_shipping_databases
msdb log_shipping_monitor
msdb log_shipping_plan_databases
msdb log_shipping_plan_history
msdb log_shipping_plans
msdb log_shipping_primaries
msdb log_shipping_secondaries
msdb logmarkhistory
msdb mswebtasks
msdb restorefile
msdb restorefilegroup
msdb restorehistory
msdb RTblClassDefs
msdb RTblClassExtension
msdb RTblDatabaseVersion
msdb RTblDBMProps
msdb RTblDBXProps
msdb RTblDTMProps
msdb RTblDTSProps
msdb RTblEnumerationDef
msdb RTblEnumerationValueDef
msdb RTblEQMProps
msdb RTblGENProps
msdb RTblIfaceDefs
msdb RTblIfaceHier
msdb RTblIfaceMem
msdb RTblMDSProps
msdb RTblNamedObj
msdb RTblOLPProps
msdb RTblParameterDef
msdb RTblPropDefs
msdb RTblProps
msdb RTblRelColDefs
msdb RTblRelshipDefs
msdb RTblRelshipProps
msdb RTblRelships
msdb RTblScriptDefs
msdb RTblSIMProps
msdb RTblSites
msdb RTblSumInfo
msdb RTblTFMProps
msdb RTblTypeInfo
msdb RTblTypeLibs
msdb RTblUMLProps
msdb RTblUMXProps
msdb RTblVersionAdminInfo
msdb RTblVersions
msdb RTblWorkspaceItems
msdb sqlagent_info
msdb sysalerts
msdb syscachedcredentials
msdb syscategories
msdb sysdbmaintplan_databases
msdb sysdbmaintplan_history
msdb sysdbmaintplan_jobs
msdb sysdbmaintplans
msdb sysdownloadlist
msdb sysdtscategories
msdb sysdtspackagelog
msdb sysdtspackages
msdb sysdtssteplog
msdb sysdtstasklog
msdb sysjobhistory
msdb sysjobs
msdb sysjobschedules
msdb sysjobservers
msdb sysjobsteps
msdb sysnotifications
msdb sysoperators
msdb systargetservergroupmembers
msdb systargetservergroups
msdb systargetservers
msdb systaskids
Database TABLE_NAME
---------- --------------------------------------
Northwind Categories
Northwind CustomerCustomerDemo
Northwind CustomerDemographics
Northwind Customers
Northwind dtproperties
Northwind Employees
Northwind EmployeeTerritories
Northwind Order Details
Northwind Orders
Northwind Products
Northwind Region
Northwind Shippers
Northwind Suppliers
Northwind Territories
Northwind TestMoney
Database TABLE_NAME
---------- --------------------------------------
pubs authors
pubs discounts
pubs employee
pubs jobs
pubs pub_info
pubs publishers
pubs roysched
pubs sales
pubs stores
pubs titleauthor
pubs titles
Database TABLE_NAME
---------- --------------------------------------
*/
model e tempdb non hanno tabelle quindi ottengo un result set vuoto.
Per maggiori informazioni leggi i seguenti paragrafi dei Books Online:
"SCHEMATA"
http://msdn.microsoft.com/library/en-us/tsqlref/ts_ia-iz_5s69.asp
"TABLES"
http://msdn.microsoft.com/library/en-us/tsqlref/ts_ia-iz_56lv.asp
SQL Server 2005 offre tutte una serie di viste che ci permettono di interagire in modo più "stretto" con il DBMS come ad esempio monitorare in modo estremamente dettagliato quello che sta accadendo in ogni istante.
Queste viste e funzioni prendono il nome di Dynamic Management Views and Functions.
Le INFORMATION_SCHEMA views sono ancora presenti ma non sono state aggiornate con le nuove funzionlità introdotte; le "vecchie" tabelle di sistema di SQL Server 2000 sono state rimappate in una serie di viste chiamate Compatibility Views e andrebbero utilizzate solo per garantire la compatibilità di qualche applicazione *scritta male* che necessitava un accesso diretto alle tabelle di sistema.
SQL Server 2005 introduce un numero considerevole di nuove viste chiamate Catalog Views che ci permettono di accedere a tutti i metadati del DB Engine in modo completo e molto efficiente.
Nel tuo caso andremo ad utilizzare la Catalog View sys.databases per recuperare l'elenco dei database:
USE master;
GO
SELECT [name] AS [Database]
FROM sys.databases;
GO
/* Output:
Database
--------------------
master
tempdb
model
msdb
ReportServer
ReportServerTempDB
AdventureWorksDW
AdventureWorks
(8 row(s) affected)
*/
Per quanto riguarda le tabelle utilizzeremo... prova un po' ad indovinare... la Catalog View sys.tables:
USE AdventureWorks;
GO
SELECT [name] AS TableName
FROM sys.tables;
GO
/* Output:
TableName
-----------------------------------
ProductProductPhoto
StoreContact
Address
ProductReview
TransactionHistory
AddressType
ProductSubcategory
AWBuildVersion
TransactionHistoryArchive
ProductVendor
BillOfMaterials
UnitMeasure
Vendor
PurchaseOrderDetail
Contact
VendorAddress
VendorContact
PurchaseOrderHeader
ContactCreditCard
WorkOrder
ContactType
CountryRegionCurrency
WorkOrderRouting
CountryRegion
CreditCard
Culture
Currency
SalesOrderDetail
CurrencyRate
Customer
SalesOrderHeader
CustomerAddress
Department
Document
Employee
SalesOrderHeaderSalesReason
SalesPerson
EmployeeAddress
EmployeeDepartmentHistory
EmployeePayHistory
SalesPersonQuotaHistory
Illustration
SalesReason
Individual
SalesTaxRate
JobCandidate
Location
SalesTerritory
Product
SalesTerritoryHistory
ScrapReason
Shift
ProductCategory
ShipMethod
ProductCostHistory
ProductDescription
ShoppingCartItem
ProductDocument
ProductInventory
SpecialOffer
ProductListPriceHistory
SpecialOfferProduct
ProductModel
StateProvince
ProductModelIllustration
DatabaseLog
ProductModelProductDescriptionCulture
ErrorLog
Store
ProductPhoto
(70 row(s) affected)
*/
Analogamente a prima potrai ricorrere alla stored procedure sp_MSforeachdb per ciclare automaticamente su tutti i database dell'istanza:
EXEC dbo.sp_MSforeachdb '
USE ?;
SELECT [name] AS TableName
FROM sys.tables;
'
GO
Per maggiori informazioni leggi i seguenti paragrafi dei Books Online:
"sys.databases (Transact-SQL)"
http://msdn2.microsoft.com/it-it/library/ms178534.aspx
"sys.tables (Transact-SQL)"
http://msdn2.microsoft.com/it-it/library/ms187406.aspx
Bene, dovrebbe bastare
Ciao!
--
Lorenzo Benaglia
Microsoft MVP - SQL Server
http://blogs.dotnethell.it/lorenzo/
http://italy.mvps.org