Solved

Ado error with

Posted on 2011-03-24
4
324 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
4 Comments
 
LVL 19

Expert Comment

by:Rikin Shah
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Thank you.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

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.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

763 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

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now