我有一个视图“TableInformationView”。
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
)
编辑: !=签名已得到纠正,但这没有任何区别。
任何人都可以为我提供解决方案,以便不包括列的额外不需要的行表示。
谢谢。
答案 0 :(得分:1)
如果要查询获取唯一表格,列组合的查询,可以使用此查询:
SELECT *
FROM (
SELECT a.*,
ROW_NUMBER() OVER(PARTITION BY a.SchemaName,a.BaseTableName,a.ColumnName ORDER BY TableName DESC) rnk
FROM TableInformationView a
) a
WHERE rnk = 1