尝试在另一个表的日期之间提取新的SQL对象

时间:2013-12-03 20:17:24

标签: sql sql-server sql-server-2008-r2

我有一个查询,它从sys表中提取信息,以生成在我们的环境中创建的新对象的列表。我需要做的是查询的最后一部分需要能够查看另一个表并拉出3个最新的记录,并使用这些记录中的日期来仅显示自这3个日期以来创建的对象。在我的测试中,我继续遇到“Subquery返回超过1的值”任何帮助将不胜感激。

编辑: 我目前正在运行SQL 2008 R2 查询现在按原样运行,但只提取最近的日期,我需要它从最近3个日期提取所有内容。

SELECT
    a.name AS ObjectName, b.name AS ParameterName, c.name AS DataType,
    b.isnullable AS [Allow Nulls?], a.crdate AS CreateDate,
    CASE WHEN d .name IS NULL THEN 0 ELSE 1 END AS [PKey?],
    CASE WHEN e.parent_object_id IS NULL THEN 0 ELSE 1 END AS [FKey?],
    CASE WHEN e.parent_object_id IS NULL THEN '-' ELSE g.name END AS [Ref Table],
    CASE WHEN h.value IS NULL THEN '-' ELSE h.value END AS Description, 
    c.length AS FieldSize, a.replinfo AS IsReplicated, 
    CASE a.xtype WHEN 'V' THEN 'View' WHEN 'P' THEN 'StoredProcedure' WHEN 'FN' THEN 'ScalarFunction' WHEN 'F' THEN 'ForeignKey' WHEN 'U' THEN 'Table' WHEN
                      'TR' THEN 'Trigger' WHEN 'TT' THEN 'TableType' WHEN 'PK' THEN 'PrimaryKey' END AS ObjectType
FROM
    sys.sysobjects AS a
    INNER JOIN sys.syscolumns AS b ON a.id = b.id
    INNER JOIN sys.systypes AS c ON b.xtype = c.xtype
    LEFT OUTER JOIN
        (SELECT so.id, sc.colid, sc.name
        FROM
            sys.syscolumns AS sc
            INNER JOIN sys.sysobjects AS so ON so.id = sc.id
            INNER JOIN sys.sysindexkeys AS si ON so.id = si.id AND sc.colid = si.colid
        WHERE (si.indid = 1)) AS d ON a.id = d.id AND b.colid = d.colid
    LEFT OUTER JOIN sys.foreign_key_columns AS e ON a.id = e.parent_object_id AND b.colid = e.parent_column_id
    LEFT OUTER JOIN sys.objects AS g ON e.referenced_object_id = g.object_id
    LEFT OUTER JOIN sys.extended_properties AS h ON a.id = h.major_id AND b.colid = h.minor_id
WHERE        (a.type = 'U' OR
                     a.type = 'V' OR
                     a.type = 'F' OR
                     a.type = 'PK' OR
                     a.type = 'P' OR
                     a.type = 'FN' OR
                     a.type = 'TT' OR
                     a.type = 'TR') AND 
                     (a.crdate >
                         (SELECT        TOP (1) DeployDate
                           FROM            OtherTable.dbo.Tracking 
                           ORDER BY DeployDate DESC))
ORDER BY CreateDate DESC

1 个答案:

答案 0 :(得分:2)

如果我正确理解您的问题,您需要跟踪表中最后3个日期的最小值。

如果是这样,你可以这样做......

(a.crdate >
      (SELECT        Min(topthree.DeployDate)
       FROM         (select Top 3 DeployDate
                     From dbo.Tracking 
                     ORDER BY DeployDate DESC
                    ) as topthree   
       )
)