2014-04-20 81 views
0

我有一個簡單的SQL查詢是這樣的:將普通SQL放入存儲過程時出現奇怪的SQL錯誤。錯誤:無效的對象名稱

SELECT   
    Users.userEmail AS registredEmail, 
    Status.statusName AS userActiveStatus, 
    Roles.roleName AS roleAssigned, 
    Users.userID AS uID 
FROM 
    Users 
INNER JOIN 
    Status ON Users.userStatus = Status.statusID 
INNER JOIN 
    Roles ON Users.userRole = Roles.roleID 
WHERE 
    (Users.companyID = 'D77VD') 

由於where條件是一個變量,把這個SQL存儲過程是這樣的:

CREATE PROCEDURE [usp_Users_12_CompanyUserGridview] 
    @companyID varchar(20) 
AS 
    SELECT   
     Users.userEmail AS registredEmail, 
     Status.statusName AS userActiveStatus, 
     Roles.roleName AS roleAssigned, 
     Users.userID AS uID 
    FROM    
     Users 
    INNER JOIN 
     Status ON Users.userStatus = Status.statusID 
    INNER JOIN 
     Roles ON Users.userRole = Roles.roleID 
    WHERE 
     (Users.companyID = @companyID) 

但奇怪的是與where值「D77VD」平原SQL運行得很好,但是當我運行此存儲過程,並通過相同的值參數,它給我一個錯誤

Invalid object name 'Users'

回答

3

其中一個應解決您的問題。

1.確認您已經(錯不在「主」)創建的程序在同一個數據庫
2.Try添加架構名稱表像「dbo.User」用戶',而不是簡單的「用戶」

EX:

CREATE PROCEDURE [usp_Users_12_CompanyUserGridview] 
@companyID varchar(20) 
AS 
SELECT  dbo.Users.userEmail AS registredEmail, Status.statusName AS userActiveStatus, Roles.roleName AS roleAssigned, dbo.Users.userID AS uID 
FROM   dbo.Users INNER JOIN 
         Status ON dbo.Users.userStatus = Status.statusID INNER JOIN 
         Roles ON dbo.Users.userRole = Roles.roleID 
WHERE (dbo.Users.companyID = @companyID) 

如果您的問題仍然沒有解決,請讓我知道。

+0

+1對你來說,有同樣的問題,花了很多小時試圖得到什麼是錯的。 – avb

0

@Suvendu Shekhar Giri -very nice catch!

@ user1889838對所有連接表使用模式名稱是非常好的做法....如果不使用模式名稱,名爲Status的表可能也會出現錯誤。

相關問題