Solved

Ado error with

Posted on 2011-03-24
4
330 Views
Last Modified: 2012-06-27
Hi, I'm using asp.net 3.5, c#
I don't know why I get this error.  Thank you.
I got the following error at:             adapter.Fill(ds, tableName);

System.Data.SqlClient.SqlException was unhandled by user code
  Message="Must declare the table variable \"@tableName\"."
  Source=".Net SqlClient Data Provider"
  ErrorCode=-2146232060
  Class=15
  LineNumber=1
  Number=1087
  Procedure=""
  Server=".\\SQLEXPRESS"
  State=2
  StackTrace:
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
       at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
       at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
       at System.Data.SqlClient.SqlDataReader.get_MetaData()
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
       at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
       at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
       at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
       at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
       at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
       at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable)
       at AdaptDAO.FillDataSet(SqlCommand cmd, String tableName, DataSet ds) in c:\Projects\AdaptSurvey\App_Code\AdaptDAO.cs:line 51
       at AdaptDAO.SelectFromATable(String tableName, DataSet ds) in c:\Projects\AdaptSurvey\App_Code\AdaptDAO.cs:line 40
       at AdaptDAO.SelectFromTables(List`1 tableNames) in c:\Projects\AdaptSurvey\App_Code\AdaptDAO.cs:line 29
       at Admin_Manage_Accounts.Page_Load(Object sender, EventArgs e) in c:\Projects\AdaptSurvey\Admin\ManageAccounts.aspx.cs:line 20
       at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
       at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
       at System.Web.UI.Control.OnLoad(EventArgs e)
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException:

public DataSet SelectFromTables(List<string> tableNames)
    {
        DataSet ds = new DataSet();
        foreach (string tableName in tableNames)
        {
            SelectFromATable(tableName, ds);
        }
        return ds;
    }

    private void SelectFromATable(string tableName, DataSet ds)
    {
        string query = "select * from @tableName";
        SqlCommand cmd = new SqlCommand(query);
        cmd.Parameters.Add("@tableName", SqlDbType.NVarChar);
        cmd.Parameters["@tableName"].Value = tableName;
        FillDataSet(cmd, tableName, ds);
    }

    private void FillDataSet(SqlCommand cmd, string tableName, DataSet ds)
    {
        SqlConnection con = new SqlConnection(connectionString);
        cmd.Connection = con;
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        try
        {
            con.Open();
            adapter.Fill(ds, tableName);

        }
        finally
        {
            con.Close();
            con.Dispose();
        }
    }

Open in new window

0
Comment
Question by:lapucca
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
4 Comments
 
LVL 19

Expert Comment

by:Rikin Shah
ID: 35212876
StringBuilder query = new StringBuilder();
query.Append("Declare @tableName VARCHAR(100)");
query.Append("select * from @tableName");
SqlCommand cmd = new SqlCommand(query.ToString());

Open in new window


Try this.
0
 
LVL 39

Accepted Solution

by:
Pratima Pharande earned 250 total points
ID: 35212877
That is because you cannot pass the table name as a parameter. You can build a dynamic SQL statement and then integrate the variable.
like this
    private void SelectFromATable(string tableName, DataSet ds)
    {
        string query = "select * from" &  tableName;";
        SqlCommand cmd = new SqlCommand(query);
        FillDataSet(cmd, tableName, ds);
    }

And even you want use cmd then use Store procedure

Store procedure
create procedure [dbo].[GetDataFromTable]
(
@tablename varchar(50)
)
as
begin
EXEC('Select * from '+ @tablename)
end

To call it
    private void SelectFromATable(string tableName, DataSet ds)
    {
        string query = "GetDataFromTable";
        SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.StoredProcedure   ;
        cmd.Parameters.Add("@tableName", SqlDbType.NVarChar);
        cmd.Parameters["@tableName"].Value = tableName;
        FillDataSet(cmd, tableName, ds);
    }
0
 
LVL 1

Assisted Solution

by:Muralidharand
Muralidharand earned 250 total points
ID: 35212884
You can not pass table name as parameter. If you want to like that then you need to change the query.

1) string query = "select * from "+ tableName;

  private void SelectFromATable(string tableName, DataSet ds)
    {
        string query = "select * from "+ tableName;
        SqlCommand cmd = new SqlCommand(query);
        FillDataSet(cmd, tableName, ds);
    }

2) second way is create a sp in sql server and pass the table name as parameter.

SQL Procedure
create proc proc1
@tableName as nvarchar(100)
as
declare @query as nvarchar(max)

set @query ='select * from ' + @tableName
EXECUTE  sp_executesql  @query

--exec proc1 'table'

  private void SelectFromATable(string tableName, DataSet ds)
    {
        string query = "Proc1";
        SqlCommand cmd = new SqlCommand(query);
        cmd.Commandtype= Commantype.StoredProcedure
        cmd.Parameters.Add("@tableName", SqlDbType.NVarChar);
        cmd.Parameters["@tableName"].Value = tableName;      
        FillDataSet(cmd, tableName, ds);
    }


Hope this helps you.
0
 

Author Closing Comment

by:lapucca
ID: 35212983
Thank you.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
In this video, viewers will be given step by step instructions on adjusting mouse, pointer and cursor visibility in Microsoft Windows 10. The video seeks to educate those who are struggling with the new Windows 10 Graphical User Interface. Change Cu…
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…

724 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question