子查询返回的值超过1。子查询时不允许这样做

时间:2017-12-22 09:24:08

标签: sql-server reporting-services sccm

我正在尝试使用SQL从SCCM返回Windows更新合规性数据,我从内置的SSRS报告中提取了查询。

不是为每个@colname(计算机组)运行单独的查询,而是通过将@colname声明为表并插入多个值来尝试合并为一个查询。

SQL中返回的错误是:

  

Msg 512,Level 16,State 1,Line 6
  子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

我的代码:

DECLARE @title VARCHAR(500);
DECLARE @colname TABLE (name VARCHAR(100));

SET @title = 'ADR | Workstation Software Updates 2017-12-14 09:01:38';

INSERT INTO @colname   
VALUES ('All Alpha Workstations'), ('All Beta Workstations'), ('All Delta Workstations');

SELECT DISTINCT
    COUNT(*) [Total Clients], li.title, coll.name,
    SUM(CASE WHEN ucs.status = 3 OR ucs.status = 1 THEN 1 ELSE 0 END) AS 'Installed / Not Applicable',
    SUM(CASE WHEN ucs.status = 2 THEN 1 ELSE 0 END) AS 'Required',
    SUM(CASE WHEN ucs.status = 0 THEN 1 ELSE 0 END) as 'Unknown',
    ROUND((CAST(SUM(CASE WHEN ucs.status = 3 OR ucs.status = 1 THEN 1 ELSE 0 END) AS float) / COUNT(*)) * 100, 2) AS 'Success %',
    ROUND((CAST(COUNT(CASE WHEN ucs.status NOT IN ('3', '1') THEN '*' END) AS FLOAT) / COUNT(*)) * 100, 2) AS 'Not Success%'
FROM
    v_Update_ComplianceStatusAll UCS
INNER JOIN
    v_r_system sys ON ucs.resourceid = sys.resourceid
INNER JOIN 
    v_FullCollectionMembership fcm ON ucs.resourceid = fcm.resourceid
INNER JOIN
    v_collection coll ON coll.collectionid = fcm.collectionid
INNER JOIN
    v_AuthListInfo LI ON ucs.ci_id = li.ci_id
WHERE 
    li.title = @title 
    AND coll.name = (SELECT name FROM @colname) --and ucs.status=2
GROUP BY
    li.title, coll.name
ORDER BY
    1

任何帮助表示赞赏。 感谢

2 个答案:

答案 0 :(得分:4)

子查询select name from @collname会返回多个值,这就是您无法使用=的原因。

使用IN谓词代替=

where li.title=@title and coll.name in (select name from @collname)

答案 1 :(得分:0)

为什么要使用Table变量?没有必要(表变量总是预计返回1行,除非你使用2017年的100行)。 可以对查询的性能产生重大影响。

只是做:

and coll.name IN ('All Alpha Workstations','All Beta Workstations','All Delta Workstations')