简体   繁体   中英

invalid object name sql exception for table name in c#

I wrote this code, but it doesn't work. Gives Invalid object name 'Inventory'`. Any Suggestion?

 using (SqlConnection cn = new SqlConnection())
        {
            cn.ConnectionString =
            @"Data Source=(local);Integrated Security=SSPI;" +
            "Initial Catalog=AutoLot";
            cn.Open();
            string strSQL = "Select * From Inventory";
            SqlCommand myCommand = new SqlCommand(strSQL, cn);
            // Obtain a data reader a la ExecuteReader().
            using (SqlDataReader mydatareader = mycommand.ExecuteReader())
            {}

签入数据库清单表是否存在,如果存在,则两个名称应该相同

If you've checked all your database settings, access rights and table definitions and still cannot get rid of that error?

It's because ASP.net cannot understand your SQL query - as shocking as that may sound.

I had the same problem, with UPDATE statements wanting to use aliases and not the usually expected dbo.myTable name definitions.

The simplest way to avoid this situation, where asp.net just doesn't parse SQL like SQL Server would (!!), is to place the code into a Stored Procedure .

This was my SQL directly from SQL Server 2005 and it worked perfectly as is...

UPDATE tsa
SET tsa.ActionComplete = @ActionComplete,
    tsa.CompleteDate = GETDATE(),
    tsa.Notes = @ActionNotes
FROM blahblah
WHERE blahblah

But for what ever reason, the ASP.net parser inside the SqlDataSource control could not make sense of it (even though it ran perfectly inside the GUI's Test Query feature!).

I was getting

invalid object name in 'tsa'

So I placed the lot inside a Stored Procedure...

USE [mydatabase];
GO
SET  ANSI_NULLS ON;
GO
SET  QUOTED_IDENTIFIER ON;
GO
ALTER PROCEDURE [dbo].[spTETupdateActions]
    @StudentID VARCHAR(10),
    @ActionComplete INT = 0,
    @ActionNotes VARCHAR(MAX),
    @TETmeetingID INT,
    @WeekNo INT,
    @TETID INT,
    @TETdate DATETIME,
    @ActionItem VARCHAR(MAX)
    WITH
    EXEC AS CALLER AS
UPDATE tsa
SET tsa.ActionComplete = @ActionComplete,
    tsa.CompleteDate = GETDATE(),
    tsa.Notes = @ActionNotes
FROM blahblah
WHERE blahblah
GO

And voila! No more errors! Why? Because the parsing of the SQL is done inside SQL Server not ASP.net!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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