考虑这个CTE
;WITH Columns AS
(
SELECT object_id AS TableId, Name AS ColumnName
FROM SYS.columns
),
Tables AS
(
SELECT S.NAME AS SchemaName, T.NAME AS TableName, object_id AS TableId
FROM sys.tables T
INNER JOIN sys.schemas S ON S.schema_id = T.schema_id
)
SELECT T.SchemaName, T.TableName, C.ColumnName
FROM Tables T
INNER JOIN Columns C ON T.TableId = C.TableId
我想要做的是将列的结果限制为前三个(例如按字母顺序排列)
所以如果我有1个模式(例如dbo)和2个表TableX& TableY有4个cols,每个ColA,ColB,ColC,ColD我的结果都是
之类的东西 dbo TableX ColA
dbo TableX ColB
dbo TableX ColC
dbo TableY ColA
dbo TableY ColB
dbo TableY ColC
schema_a
答案 0 :(得分:1)
看起来我找到了答案: - )
Select Top row of 2nd table in SQL Join
;WITH Columns AS
(
SELECT
row_number() over (partition by object_id ORDER BY Name DESC) as RowNumber,
object_id AS TableId,
Name AS ColumnName
FROM SYS.columns
),
Tables AS
(
SELECT
S.NAME AS SchemaName,
T.NAME AS TableName, object_id AS TableId
FROM sys.tables T
INNER JOIN sys.schemas S ON S.schema_id = T.schema_id
)
SELECT T.SchemaName, T.TableName, C.RowNumber, C.ColumnName
FROM Tables T
INNER JOIN Columns C ON T.TableId = C.TableId
where RowNumber BETWEEN 1 AND 3