twitter facebook

SQLServer の列名取得

以下のクエリでカラム名を取得できます。
SELECT *
FROM   sys.columns
WHERE  object_id = (
	SELECT object_id
	FROM   sys.tables
	WHERE  name = 'テーブル名'
)
出力例
object_idnamecolumn_idsystem_type_iduser_type_idmax_lengthprecisionscalecollation_nameis_nullableis_ansi_paddedis_rowguidcolis_identityis_computedis_filestreamis_replicatedis_non_sql_subscribedis_merge_publishedis_dts_replicatedis_xml_documentxml_collection_iddefault_object_idrule_object_idis_sparseis_column_set
388196433ticket_id11271278190NULL0001000000000000
388196433ticket_status44848130NULL100000000000404196490000
388196433ticket_price756564100NULL1000000000000000
388196433ticket_create_time1061618233NULL1000000000000000
388196433ticket_update_time1161618233NULL1000000000000000
SELECT 
ORDINAL_POSITION, COLUMN_NAME, DATA_TYPE, TABLE_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'テーブル名'
ORDERBY ORDINAL_POSITION
出力例
1ticket_idbigintt_ticket
4ticket_statustinyintt_ticket
7ticket_priceintt_ticket
10ticket_create_timedatetimet_ticket
11ticket_update_timedatetimet_ticket
主キーも取得する場合の例
SELECT T1.ORDINAL_POSITION as no, T1.COLUMN_NAME as field, T1.DATA_TYPE as type, T1.TABLE_NAME as tbl, 
 CASE WHEN T2.COLUMN_NAME IS NULL THEN '' ELSE 'PRI' END as 'key'

FROM INFORMATION_SCHEMA.COLUMNS T1
LEFT JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE T2 
	ON T1.TABLE_NAME=T2.TABLE_NAME AND T1.COLUMN_NAME=T2.COLUMN_NAME 
WHERE T1.TABLE_NAME = 'テーブル名'
ORDER BY T1.ORDINAL_POSITION
出力例
nofieldtypetblkey
1ticket_idbigintt_ticketPRI
4ticket_statustinyintt_ticket
7ticket_priceintt_ticket
10ticket_create_timedatetimet_ticket
11ticket_update_timedatetimet_ticket
AUTHOR
@えのえの
最終更新日 2021/02/20
FAVORITE good stock
LINK TAG
記法を見る
1732998521