在sql中使用连接计数查询

时间:2014-01-05 18:38:16

标签: sql sql-server count

我尝试在SQL中创建一个计数查询,当任何用户在asp.net上传新文档时,我会尝试向主管,经理和导演显示通知

查询

ALTER procedure [dbo].[countdocuments]
   @DepID int
as
    SELECT 
       COUNT(*),
       Designation.DesigID
    FROM DocumentInfo
    INNER JOIN dbo.Userss ON dbo.Userss.DesigID = dbo.Designation.DesigID
    WHERE 
       Userss.DesigID = 'Finance'

但是当我执行它时,会发生以下错误

  

Msg 4104,Level 16,State 1,Procedure countdocuments,Line 7   多部分标识符" dbo.Designation.DesigID"无法受约束   消息4104,级别16,状态1,程序计数文档,第5行   多部分标识符" Designation.DesigID"无法受约束。

好的,这是我的designation

DesigID   DesigType
  1       SuperVisor
  2       Manager
  3       Director
  4       BasicUsers

这是documentinfo

DocID  DocDescrit  DocName UploadedDate Uploadfile DocTypeID DepID ApproveID UploadedBy UserID
32  asp.net codescomputer 2013-12-30 22:30:00.623    details.docx   1   2   1amna   24

这是userss

UserID UserName Password UserTypeID DepID CreateDate Email PhoeNumber DesigID
21  john    abc 2   NULL    NULL    2013-12-02 22:01:03.903 NULL    abc@hotmail.com 12313   4

当我尝试这个查询时

ALTER procedure [dbo].[countdocuments]
    @DepID int
as
BEGIN
    SET NOCOUNT ON;

    SELECT 
        COUNT(*) AS Cnt, Designation.DesigID
    FROM 
        Designation 
    INNER JOIN 
        dbo.Userss ON dbo.Userss.DesigID = dbo.Designation.DesigID
    WHERE 
        Userss.DesigID = @DepID
    GROUP BY 
        Designation.DesigID
END

当我尝试执行与@depid = 4类似的操作时,这样就向我显示了这一点,我不明白4来自哪里......

Cnt  DesigID
 4     4

2 个答案:

答案 0 :(得分:0)

ALTER procedure [dbo].[countdocuments]
@DepID int
as
BEGIN
  SET NOCOUNT ON;
    SELECT COUNT(*) AS Cnt,Designation.DesigID
    FROM DocumentInfo inner join dbo.Userss 
    on dbo.Userss.DesigID = dbo.DocumentInfo.DesigID
    WHERE Userss.DesigID = @DepID
    GROUP BY DocumentInfo.DesigID

END

您在JOIN子句和ON子句中有不同的表名。假设您的DesigID表格中有DocumentInfo列,我已尝试修复此问题。

答案 1 :(得分:0)

查看您的评论,请尝试以下

ALTER procedure [dbo].[countdocuments]
@DepID int
as
BEGIN
SET NOCOUNT ON;
SELECT COUNT(*) AS Cnt,Designation.DesigID
FROM Designation left join dbo.Userss 
on dbo.Userss.DesigID = dbo.Designation.DesigID
left Join DocumentInfo on Userss.UserId= DocumentInfo.UserId and Designation.DepId = DocumentInfo.DepId
WHERE Userss.DesigID = @DepID
GROUP BY Designation.DesigID

END

或尝试以下

Looking at your comment try following

ALTER procedure [dbo].[countdocuments]
@DepID int
as
BEGIN
SET NOCOUNT ON;
SELECT COUNT(*) AS Cnt,Designation.DesigID
FROM DocumentInfo  left Join Userss on DocumentInfo.UserId = Userss.UserId
left Join Designation on DocumentInfo.DepId = Designation.DeptId
and Designation.DesigID = Userss.DesigId
WHERE Userss.DesigID = @DepID
GROUP BY Designation.DesigID

END