Determinare i nomi e i tipi dei campi di una tabella SQLServer 2005 via SQL

Può capitare di avere necessità di dover costruire dinamicamente delle query SQL anche complesse senza conoscere a priori la struttura della tabella / tabelle su cui si andrà a insistere, ma solo il loro nome.

Un metodo empirico per ottenere queste informazioni (e molto altro...) è quello di imitare il designer dei tableadapter di VS2005 che utilizza la seguente query (modificate il nome "test" con il nome del vostro db e il nome "ana_clienti" con il nome della vostra tabella):

select
 col.name, 
 st.name as DT_name,  
 case when (st.name in ('nchar', 'nvarchar') and (col.max_length > 0))  then col.max_length / 2 else col.max_length end,  col.precision, 
 col.scale, 
 bt.name as BT_name, 
 col.is_nullable, 
 col.is_identity,col.is_rowguidcol, 
 OBJECTPROPERTY(col.default_object_id, N'IsDefaultCnst') as is_defcnst,  
 CONVERT(bit, case when(cmc.column_id is null) then 0 else 1 end) as is_computed, 
 case when(cmc.column_id is null) then null else cmc.definition end as formular, 
 col.collation_name, 
 col.system_type_id
from
 test.sys.all_columns col  left outer join
 test.sys.types st on st.user_type_id = col.user_type_id left outer join
 test.sys.types bt on bt.user_type_id = col.system_type_id  left outer join
 test.sys.identity_columns idc on idc.object_id = col.object_id and idc.column_id = col.column_id  left outer join
 test.sys.computed_columns cmc on cmc.object_id = col.object_id and cmc.column_id = col.column_id  where col.object_id = object_id(N'test.dbo.ana_clienti') 
order by
 col.column_id

Published venerdì 13 luglio 2007 11.56 by admin
Filed under: ,

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required) 
Powered by Community Server (Commercial Edition), by Telligent Systems