如何从SQL Server存储过程访问单独的数据库

时间:2015-04-09 17:34:11

标签: sql sql-server stored-procedures

我正在尝试运行以下代码但遇到错误:

  

无法绑定多部分标识符

我认为这是因为尝试从单独的数据库访问数据库表,但它位于同一台服务器上。有什么想法吗?

SELECT DISTINCT
    @ActiveStudents2 = COUNT([ActivityHistory].[dbo].[tblActivityCounts].[id])
FROM  
    dbo.tblSchools 
INNER JOIN 
    dbo.tblStudentSchool ON dbo.tblSchools.schoolid = dbo.tblStudentSchool.schoolid 
INNER JOIN 
   dbo.tblStudentPersonal ON dbo.tblStudentSchool.id = dbo.tblStudentPersonal.id
WHERE 
     dbo.tblStudentSchool.schoolid IN (@tempschoolid) 
     AND tblStudentSchool.graduationyear IN (SELECT Items 
                                             FROM FN_Split(@gradyears, ',')) 
     AND ([ActivityHistory].[dbo].[tblActivityCounts].[datetimechanged] >= @datefrom 
     AND [ActivityHistory].[dbo].[tblActivityCounts].[datetimechanged] <= @dateto)

当我尝试访问作为单独数据库的活动历史记录数据库中的tblActivityCounts表时,会发生错误。我甚至尝试将其作为sa运行,但它不起作用。没有任何拼写错误。任何帮助表示赞赏。谢谢!

3 个答案:

答案 0 :(得分:2)

您没有加入ActivityHistory表。这就是为什么查询不知道从哪里访问tblActivityCounts表。

答案 1 :(得分:0)

正如Aleem所说,你没有加入另一张桌子。我还建议利用表别名来使您的代码更具可读性......当您稍后再回到它时,可以更容易地弄清楚您正在做什么。 根据tblActivityCounts与其他表的关系,您可以执行以下操作:

SELECT      @ActiveStudents2 = COUNT(ActivityHistory.dbo.tblActivityCounts.id)
FROM        dbo.tblSchools as Schools
INNER JOIN  dbo.tblStudentSchool as Students
    ON      Schools.schoolid = Students.schoolid
INNER JOIN  dbo.tblStudentPersonal as Personel
    ON      Students.id = Personel.id
INNER JOIN  ActivityHistory.dbo.tblActivityCounts as Activity
    ON      Activity.studentid = Students.id -- Depending on how tblActivityCounts relates to the other tables
WHERE       Students.schoolid IN (@tempschoolid)
    AND     tblStudentSchool.graduationyear IN (SELECT Items FROM FN_Split(@gradyears, ',')) 
    AND     Activity.datetimechanged >= @datefrom 
    AND     Activity.datetimechanged <= @dateto

答案 2 :(得分:0)

您的查询错误。这一行:

SELECT DISTINCT
    @ActiveStudents2 = 
    COUNT([ActivityHistory].[dbo].[tblActivityCounts].[id])

将检索tblActivityCounts表中的所有ID并计算它们,但在其余查询中没有引用。你必须JOIN使用此表并引用它来计算。另外,我建议你使用别名。

这样的事情:

SELECT DISTINCT
    @ActiveStudents2 = COUNT(ah.[id])
FROM dbo.tblSchools s
INNER JOIN dbo.tblStudentSchool ss ON s.schoolid = ss.schoolid 
INNER JOIN dbo.tblStudentPersonal sp ON s.id = sp.id
INNER JOIN [ActivityHistory].[dbo].[tblActivityCounts] ah ON s.acIdentifier = ah.acIdentifier
WHERE ss.schoolid IN (@tempschoolid) 
     AND ss.graduationyear IN (SELECT Items 
                               FROM FN_Split(@gradyears, ',')) 
                                AND ([ActivityHistory].[dbo].[tblActivityCounts].[datetimechanged] >= @datefrom 
                                AND [ActivityHistory].[dbo].[tblActivityCounts].[datetimechanged] <= @dateto)