2009年7月2日木曜日

SQL Server DEFAULT 制約名を取得

ユーザーが定義したテーブルの各フィールドに定義されている制約名を取得する。
 
●SQL Server 2005以降
 
SELECT
 tb.id AS tb_id, --(テーブルID)
 tb.name AS tb_name, --(テーブル名)
 col.object_id AS col_id,  --(フィールドID)
 col.name AS col_name,   --(フィールド名)
 col.default_object_id AS const_id, --(制約ID)
 const.name AS const_name --(制約名)
FROM sys.columns AS col
 LEFT JOIN sysobjects AS tb ON col.object_id = tb.id
 LEFT JOIN sys.default_constraints AS const ON col.default_object_id = const.object_id
WHERE (col.object_id IN(SELECT id FROM sysobjects WHERE (xtype = 'U'))) --ユーザーテーブルのみに限定
ORDER BY tb.id
 
 
●SQL Server 2000(SQL Server 2005も可能)
 
SELECT
 tb.id as tb_id,
 tb.name as tb_name,
 col.name as col_name,
 col.cdefault as const_id,
 const.name as const_name
FROM syscolumns as col
 LEFT JOIN sysobjects as tb on col.id = tb.id
 INNER JOIN sysobjects as const on col.cdefault = const.id
WHERE tb.xtype IN('U', 'D') AND
OTDER BY tb.id
 

0 件のコメント:

Google検索