搜索多个表并生成单个可分页混合ResultSet

时间:2012-12-08 14:32:36

标签: sql sql-server-2008

我在SQL Server 2008数据库中有4个表,具有以下架构

Tutorials (TutorialID, Title, Approved, AddedDate)
Albums    (AlbumID, Title, Approved, AddedDate)
Profiles  (ProfileID, Title, Approved, AddedDate)
Polls     (PollID, Title, Approved, AddedDate)

我想提供搜索所有这些表的搜索工具,并生成一个可分页的结果集,显示所有表的混合数据。

1 个答案:

答案 0 :(得分:1)

您可能想要一个联合视图:

CREATE VIEW MixedData(Type, ID, Title, Approved, AddedDate) AS
    SELECT 'Tutorial' AS Type, TutorialID AS ID, Title, Approved, AddedDate
    UNION ALL
    SELECT 'Album'    AS Type, AlbumID    AS ID, Title, Approved, AddedDate
    UNION ALL
    SELECT 'Profile'  AS Type, ProfileID  AS ID, Title, Approved, AddedDate
    UNION ALL
    SELECT 'Poll'     AS Type, PollID     AS ID, Title, Approved, AddedDate

然后,您可以选择MixedData应用您想要的标准。 “AS类型”和“AS ID”条款并非绝对必要。