Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Ado error with

Posted on 2011-03-24
4
Medium Priority
?
333 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 1000 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 1000 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

Tech or Treat!

Submit an article about your scariest tech experience—and the solution—and you’ll be automatically entered to win one of 4 fantastic tech gadgets.

Question has a verified solution.

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

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…

604 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