Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

MSSQL and ADO.NET | Exception: “Invalid attempt to read when no data is present."

$
0
0

When trying to read the object coming back from SQL, I am given the exception "{ "Invalid attempt to read when no data is present."

C# code:

using(SqlConnection con =newSqlConnection(connection)){SqlCommand cmd =newSqlCommand("PROC", con);
cmd.CommandType=CommandType.StoredProcedure;SqlParameterParamName1=newSqlParameter("@Name1","XYZ123");SqlParameterParamName2=newSqlParameter("@Name2","1234");

cmd.Parameters.Add(ParamName1);
cmd.Parameters.Add(ParamName2);

con.Open();try{SqlDataReader rdr = cmd.ExecuteReader();while(rdr.Read()){string result = rdr["Item"].ToString();}

    rdr.Close();}catch(Exception ex){throw ex;}}

SQL dynamic query (EXEC and sp_executesql)

 ALTER PROC [dbo].[PROC]
@Name1 varchar(128),@Name2 varchar(128) ASBEGIN--DECLARE @Name1 varchar(128)='XYZ123',--@Name2 varchar(128)='1234'--DECLARE @SelectFromTable varchar(MAX) SET @SelectFromTable='SELECT [Item] FROM [dbo].['+@Name1+'] WHERE [ID] = '+@Name2+' ' EXEC (@SelectFromTable)--PRINT (@SelectFromTable)END
ALTER PROC [dbo].[PROC](@Name1 varchar(128),--for an object I would prefer to use sysname instead@Name2 varchar(128)) ASBEGIN
    DECLARE @SelectFromTable nvarchar(MAX)

    SET @SelectFromTable= N'SELECT Item
                            FROM dbo.'+ QUOTENAME(@Name1)+'
                            WHERE ID = @Name2'exec sp_executesql @SelectFromTable, N'@Name2 varchar(128)',@Name2=@Name2--PRINT (@SelectFromTable)END

WHAT I HAVE TRIED

I have tested the dynamic SQL query in SQL Server by using the PRINT function to see that I'm getting the right data back from the executed statement, and indeed I am. I have looked over my C# code but cannot find the fault there.

NOTE: Problem seems to be with the SqlDataReader (rdr). Query works with both EXEC and sp_executesql


Viewing all articles
Browse latest Browse all 1698

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>