简体   繁体   English

尝试执行存储过程时无效的对象名称错误?

[英]Invalid object name error when trying to execute stored procedure?

Not sure what the deal is I have the stored procedure named exactly what I am calling however it always gives me this invalid object error. 不确定是什么交易我的存储过程命名正是我所调用的,但它总是给我这个无效的对象错误。 Here is the connection code, the error is thrown on the second to last line there. 这是连接代码,错误是在那里的倒数第二行引发的。

SqlConnection cnstr = new SqlConnection(ConfigurationManager.ConnectionStrings["darconn"].ConnectionString);
SqlCommand sqlcmd = new SqlCommand();

sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Connection = cnstr;
sqlcmd.CommandText = "SetMapping";

String[] pullKodID = bundlelist.SelectedValue.ToString().Split(':');
int kod_id = System.Convert.ToInt32(pullKodID[0]);

sqlcmd.Parameters.Add("@kod_id", kod_id);
sqlcmd.Parameters.Add("@ell_id", courselist.Items[i].Text);
cnstr.Open();
sqlcmd.ExecuteNonQuery();
cnstr.Close();

Most likely the stored procedure isn't visible to your code because it was created/owned by a user other than dbo or the user specified in your connection string. 很可能存储过程对您的代码不可见,因为它是由dbo以外的用户或连接字符串中指定的用户创建/拥有的。

Have you tried prefixing the stored procedure name with dbo ? 您是否尝试使用dbo为存储过程名称添加前缀? For example "dbo.SetMapping". 例如“dbo.SetMapping”。

Failing that, use Management Studio/Enterprise Manager to find out who owns the stored procedure and either recreate it as dbo or update your code/connection string to use the appropriate user. 如果做不到这一点,请使用Management Studio / Enterprise Manager查找谁拥有存储过程,并将其重新创建为dbo或更新您的代码/连接字符串以使用相应的用户。

I had the same problem and it turned out that I created the stored procedure in the [master] database instead of the one I was supposed to be working on. 我遇到了同样的问题,事实证明我在[master]数据库中创建了存储过程,而不是我应该处理的那个。 Probably not your issue, but it is something to take note of. 可能不是你的问题,但需要注意的是。

sql profiler showing anything? sql profiler显示什么?

can you execute outside of the context of the app? 你可以在应用程序的上下文之外执行吗? from mgt studio or qry analyzer? 来自mgt studio还是qry analyzer?

Check the spelling of the table name(s) in the stored procedure. 检查存储过程中表名的拼写。

When saving a stored procedure it checks the names of the fiels in the tables used, but it's possible to save a stored procedure that uses a table name that doesn't exist (or is misspelled). 保存存储过程时,它会检查所用表中的fiel的名称,但是可以保存使用不存在(或拼写错误)的表名的存储过程。

Check the stored procedure to see if it is owned by 'dbo' thus the name would be 'dbo.SetMapping' and not something like 'SomeUser.SetMapping' 检查存储过程以查看它是否属于'dbo',因此名称将为'dbo.SetMapping'而不是'SomeUser.SetMapping'

I would also explicitly specify the 'dbo.' 我还会明确指定'dbo'。 in the name 在名字里

sqlcmd.CommandText = "dbo.SetMapping";

First make sure that your stored procedures actually work outside of .net. 首先确保您的存储过程实际上在.net之外工作。 If it is working just fine then consider the following... 如果工作正常,请考虑以下内容......

This error can be misleading if the object referenced works just fine, check other stored procedures you use on the same page for invalid references to the 'object' 如果引用的对象工作正常,则此错误可能会产生误导,请检查您在同一页面上使用的其他存储过程,以便对“对象”进行无效引用

The reason is it may be referencing an SQL ERROR inside a completely separate broken stored procedure that you're running on the same page. 原因是它可能在您在同一页面上运行的完全独立的损坏存储过程中引用SQL错误。 For instance, say you have a stored procedure to get the contents of a table; 例如,假设您有一个存储过程来获取表的内容; if you mistakenly join a table with the stored procedure (rather than the table the stored procedure was referencing) in another stored procedure on the same page then this error will be thrown. 如果您错误地将存储过程 (而不是存储过程所引用的表)的表连接在同一页面上的另一个存储过程中,则会抛出此错误。 Which can be confusing, since you know that the stored procedure referenced works just fine! 这可能会令人困惑,因为您知道引用的存储过程工作得很好!

I had the wrong table name inside the procedure, which was why I was getting that error. 我在程序中有错误的表名,这就是我收到错误的原因。

Example: There is a table named test2 in a procedure, with fields from the table test . 示例:过程中有一个名为test2的表,其中包含表test字段。 It looked like: 它看起来像:

insert into test2 (fields from test) values ... insert into test2 (fields from test) values ...

i have got similar problem. 我有类似的问题。 i forgot to write full path to the my actual data base. 我忘记写完我的实际数据库的完整路径。 so u have to write select *From [your data basename].[dbo].[object name] in my case in was a table object in practical named database so,select *from [practical].[dbo].[employee] same logic apply for the stored procedures as well 所以你必须写select * From [你的数据库名]。[dbo]。[对象名]在我的情况下是实际命名数据库中的一个表对象所以,从[实用]中选择*。[dbo]。[employee]同样的逻辑也适用于存储过程

What is the name of actual object that it is complaining about ? 它抱怨的实际对象的名称是什么? I have seen the same problem in a stored proc and actually there was no problem with the sproc per se - but due to a typo the name of a table used in the stored proc was wrong (the sproc name had accidentally been pasted in as the table name) so it gave back the Invalid Object name error that matched the sproc name - which was very confusing. 我在存储过程中看到了同样的问题,实际上sproc本身没有问题 - 但是由于输入错误,存储过程中使用的表的名称是错误的(sproc名称被意外地粘贴在了表名)因此它返回了与sproc名称匹配的无效对象名称错误 - 这非常令人困惑。

Try changing the sproc name and call it again from your code and see what happens - or try running the sproc directly in SQL Management Studio. 尝试更改sproc名称并从代码中再次调用它,看看会发生什么 - 或者尝试直接在SQL Management Studio中运行sproc。

If that doesn't work then be very methodical, divide and conquer - go right back to basics and check everything again end-to-end. 如果这不起作用那么非常有条理,分而治之 - 直接回到基础并再次检查端到端的一切。 Is the connection string correct, what database is it connecting to at runtime, what user id, does the sproc work in Sql management studio on its own etc 连接字符串是否正确,它在运行时连接到什么数据库,什么用户ID,sproc在Sql管理工作室中自己运行等等

Hope that helps. 希望有所帮助。

I also had the same error occuring each time I tried to insert certain data in an SQL table using ADO.Net . 每次我尝试使用ADO.Net在SQL表中插入某些数据时,我也遇到了同样的错误。 Later I discovered a trigger on the table preventing this,when I tried to execute the same command in SQL server directly. 后来当我尝试在SQL Server中直接执行相同的命令时,我在表上发现了一个阻止它的触发器。 So check that too. 所以检查一下。

For what it's worth, I had a completely different problem on .NET 4 that produced the same exception, with little useful information to diagnose it. 对于它的价值,我在.NET 4上遇到了一个完全不同的问题,产生了相同的异常,几乎没有什么有用的信息来诊断它。

I updated several tables in my DBML. 我在DBML中更新了几个表。 I may have re-loaded a stored procedure, but I don't remember doing so. 我可能已经重新加载了一个存储过程,但我不记得这样做了。

I was left with the following sproc wrapper in the designer.cs: 我在designer.cs中留下了以下sproc包装器:

[global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.GetSomeInformation", IsComposable=true)]
public IQueryable<GetSomeInformationResult> GetSomeInformation([global::System.Data.Linq.Mapping.ParameterAttribute(DbType="BigInt")] System.Nullable<long> infoId)
{
    return this.CreateMethodCallQuery<GetSomeInformationResult>(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), infoId);
}

CreateMethodCallQuery is intended for calling table-valued functions, rather than stored procedures. CreateMethodCallQuery用于调用表值函数,而不是存储过程。 I'm baffled as to why it would have changed this. 我很困惑为什么它会改变这一点。 I reverted it to use ExecuteMethodCall : 我还原它使用ExecuteMethodCall

[global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.GetSomeInformation")]
public ISingleResult<GetSomeInformationResult> GetSomeInformation([global::System.Data.Linq.Mapping.ParameterAttribute(DbType="BigInt")] System.Nullable<long> infoId)
{
    IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), infoId);
    return ((ISingleResult<GetSomeInformationResult>)(result.ReturnValue));
}

And all is well. 一切都很好。 Very strange. 很奇怪。

UPDATE: This seems to have been caused by Visual Studio deciding a stored procedure was a table-valued function when it was added to the dbml. 更新:这似乎是由Visual Studio决定存储过程在添加到dbml时是一个表值函数引起的。 I've never seen that happen before. 我以前从未见过这种情况。

The "IsComposable" flag seems to be the only way it distinguishes between stored procedures and table-values functions. “IsComposable”标志似乎是区分存储过程和表值函数的唯一方法。 Once I cleared the flag from the Function node in the dbml, Visual Studio generated correct code in the designer file. 一旦我从dbml中的Function节点清除了标志,Visual Studio就会在设计器文件中生成正确的代码。

你绝对确定你输入的名字是否正确?

This one is a long shot, but the common answers are already listed. 这是一个很长的镜头,但已经列出了常见的答案。

Rarely a script can get a different name in the catalog that in the script. 很少,脚本可以在脚本中的目录中获得不同的名称。 I believe this could cause issues similar to what you are seeing. 我相信这可能会导致类似于您所看到的问题。

The following script will check your db to see if there are items in your catalog that don't match the script. 以下脚本将检查您的数据库,以查看目录中是否有与该脚本不匹配的项目。 (You need SQL 2005 or higher for this to work) (你需要SQL 2005或更高版本才能工作)

-------------------------------------------------------------------------
-- Check Syntax of Database Objects
-- Copyrighted (2009).  Free to use as a tool to check your own code or in 
--  any software not sold. All other uses require written permission from Author
-- Author: Stephen Schaff
-------------------------------------------------------------------------
-- Turn on ParseOnly so that we don't actually execute anything.
SET PARSEONLY ON 
GO

-- Create a table to iterate through
declare @ObjectList table (ID_NUM int NOT NULL IDENTITY (1, 1), OBJ_NAME varchar(255), OBJ_TYPE char(2))

-- Get a list of most of the scriptable objects in the DB.
insert into @ObjectList (OBJ_NAME, OBJ_TYPE)
SELECT   name, type
FROM     sysobjects WHERE type in ('P', 'FN', 'IF', 'TF', 'TR', 'V')
order by type, name

-- Var to hold the SQL that we will be syntax checking
declare @SQLToCheckSyntaxFor varchar(max)
-- Var to hold the name of the object we are currently checking
declare @ObjectName varchar(255)
-- Var to hold the type of the object we are currently checking
declare @ObjectType char(2)
-- Var to indicate our current location in iterating through the list of objects
declare @IDNum int
-- Var to indicate the max number of objects we need to iterate through
declare @MaxIDNum int
-- Set the inital value and max value
select  @IDNum = Min(ID_NUM), @MaxIDNum = Max(ID_NUM)
from    @ObjectList

-- Begin iteration
while @IDNum <= @MaxIDNum
begin
  -- Load per iteration values here
  select  @ObjectName = OBJ_NAME, @ObjectType = OBJ_TYPE
  from    @ObjectList
  where   ID_NUM = @IDNum 

  -- Get the text of the db Object (ie create script for the sproc)
  SELECT @SQLToCheckSyntaxFor = OBJECT_DEFINITION(OBJECT_ID(@ObjectName, @ObjectType))

  begin try
    -- Run the create script (remember that PARSEONLY has been turned on)
    EXECUTE(@SQLToCheckSyntaxFor)
  end try
  begin catch
    -- See if the object name is the same in the script and the catalog (kind of a special error)
    if (ERROR_PROCEDURE() <> @ObjectName)
    begin
      print 'Error in ' + @ObjectName
      print '  The Name in the script is ' + ERROR_PROCEDURE()+ '. (They don''t match)'
    end

  end catch

  -- Setup to iterate to the next item in the table
  select  @IDNum = case
            when Min(ID_NUM) is NULL then @IDNum + 1
            else Min(ID_NUM)
          end  
  from    @ObjectList
  where   ID_NUM > @IDNum

end
-- Turn the ParseOnly back off.
SET PARSEONLY OFF 
GO

(As a side note, if you want to see all errors in your db add this after the if (ERROR_PROCEDURE() <> @ObjectName) block.) (另请注意,如果要查看数据库中的所有错误,请在if (ERROR_PROCEDURE() <> @ObjectName)块之后添加此错误。)

else if (ERROR_MESSAGE() <> 'There is already an object named ''' + ERROR_PROCEDURE() + ''' in the database.')
begin
  -- Report the error that we got.
  print 'Error in ' + ERROR_PROCEDURE()
  print '  ERROR TEXT: ' + ERROR_MESSAGE() 
end

Is the database using a case-sensitive collation? 数据库是否使用区分大小写的排序规则? If so, is the case in your C# code the same as the case in the database? 如果是这样,您的C#代码中的情况与数据库中的情况相同吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM