如何从存储的进程中返回rowcount - SQL Server 2012

时间:2015-04-23 06:38:50

标签: stored-procedures sql-server-2012 rdbms

我正在SQL Server 2012中编写存储过程,并在读取存储过程在匹配所有条件和连接条件后将返回的行数时遇到问题。

我的存储过程是:

SELECT DISTINCT
    COUNT(crs.CourseId) OVER() AS Recordcounts, 
    crs.CourseId,
    crs.CourseName,
    crs.CourseDescription,
    (SELECT CourseGroupName FROM CourseGroup cgrp 
     WHERE cgrp.CourseGroupId = crs.CourseGroupId) AS Category
FROM 
    Courses crs 
INNER JOIN 
    CourseRequests creq ON crs.CourseId = creq.CourseId
WHERE
    crs.Coursename <> ''''

对于其中一个条件,它返回16作为“Recordcounts”,但实际上,结果只有3行。

有人可以帮我吗?

由于

下面的屏幕截图将更清楚地了解其中一个条件的问题:enter image description here

1 个答案:

答案 0 :(得分:0)

试试这个:

;with cte as(
SELECT distinct
    crs.CourseId,
    crs.CourseName,
    crs.CourseDescription,
    (SELECT CourseGroupName FROM CourseGroup cgrp 
     WHERE cgrp.CourseGroupId = crs.CourseGroupId) AS Category
FROM 
    Courses crs 
INNER JOIN 
    CourseRequests creq ON crs.CourseId = creq.CourseId
WHERE
    crs.Coursename <> '''')

Select *, (select COUNT(CourseId) from cte) AS Recordcounts
from cte