私はビュー "TableInformationView"を持っています。T-SQLはこのクエリで重複する列を削除します
USE [AdventureWorks]
--OR ANY DATABASE
/****** Object: View [dbo].[TableInformationView] Script Date: 01/01/2011 01:17:31 ******/
IF EXISTS (SELECT *
FROM sys.views
WHERE object_id = OBJECT_ID(N'[dbo].[TableInformationView]'))
DROP VIEW [dbo].[TableInformationView]
GO
/****** Object: View [dbo].[TableInformationView] Script Date: 01/01/2011 01:17:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[TableInformationView]
AS
SELECT C.TABLE_SCHEMA AS SchemaName,
C.TABLE_NAME AS BaseTableName,
CASE
WHEN C.TABLE_SCHEMA = 'dbo' THEN C.TABLE_NAME
ELSE C.TABLE_SCHEMA + '.' + C.TABLE_NAME
END AS TableName,
C.COLUMN_NAME AS ColumnName,
C.ORDINAL_POSITION as OrdinalPosition,
C.COLUMN_DEFAULT as ColumnDefault,
C.IS_NULLABLE AS IsNullable,
C.DATA_TYPE as DataType,
ISNULL(C.CHARACTER_MAXIMUM_LENGTH, 0) as MaxLength,
TC.CONSTRAINT_TYPE AS ConstraintType,
TC.CONSTRAINT_NAME as ConstraintName,
RC.UNIQUE_CONSTRAINT_NAME as ParentConstraintName,
RC.MATCH_OPTION as MatchOption,
RC.UPDATE_RULE as UpdateRule,
RC.DELETE_RULE as DeleteRule,
TC_FK.TABLE_SCHEMA + '.' + TC_FK.TABLE_NAME 'ForeignTable'
FROM INFORMATION_SCHEMA.COLUMNS C
LEFT OUTER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU
ON C.TABLE_NAME = KCU.TABLE_NAME
AND C.COLUMN_NAME = KCU.COLUMN_NAME
AND C.TABLE_SCHEMA = KCU.TABLE_SCHEMA
AND C.ORDINAL_POSITION = KCU.ORDINAL_POSITION
LEFT OUTER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
ON KCU.TABLE_NAME = TC.TABLE_NAME
AND KCU.TABLE_SCHEMA = TC.TABLE_SCHEMA
AND KCU.CONSTRAINT_NAME = TC.CONSTRAINT_NAME
AND KCU.CONSTRAINT_SCHEMA = TC.CONSTRAINT_SCHEMA
AND KCU.CONSTRAINT_CATALOG = TC.CONSTRAINT_CATALOG
LEFT OUTER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
ON RC.CONSTRAINT_NAME = KCU.CONSTRAINT_NAME
AND RC.UNIQUE_CONSTRAINT_SCHEMA = KCU.CONSTRAINT_SCHEMA
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU_FK
ON RC.CONSTRAINT_NAME = KCU_FK.CONSTRAINT_NAME
AND RC.UNIQUE_CONSTRAINT_SCHEMA = KCU.CONSTRAINT_SCHEMA
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC_FK
ON RC.UNIQUE_CONSTRAINT_NAME = TC_FK.CONSTRAINT_NAME
AND RC.UNIQUE_CONSTRAINT_SCHEMA = TC_FK.CONSTRAINT_SCHEMA
GO
ビューは、別のテーブルの外部キーである列を除いて正常に動作します。
を参照してくださいどのように
SELECT * FROM TableInformationView
WHERE
TableInformationView.SchemaName +
TableInformationView.BaseTableName +
TableInformationView.ColumnName
IN
(
select TOP 1
TableInformationView.SchemaName +
TableInformationView.BaseTableName +
TableInformationView.ColumnName
from
TableInformationView
group by
TableInformationView.SchemaName +
TableInformationView.BaseTableName +
TableInformationView.ColumnName
having COUNT(*) > 1
)
編集:! は=記号が修正されましたが、これはどんな違いがありません。
誰かが私に解決策を提供して、不要な列の不要な行表現が含まれないようにすることができます。
ありがとうございます。
は、なぜあなたは二回INFORMATION_SCHEMA.TABLE_CONSTRAINTS' 'に参加していますか? –
2番目の方法は、関係の親テーブルを見つけることです。 –