Improve company productivity with a Business Account.Sign Up

x
?
Solved

Ado error with

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

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
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.
Hi, this video explains a free download that you can incorporate into your Access databases, or use stand-alone for contact management. Contacts -- Names, Addresses, Phone Numbers, eMail Addresses, Websites, Lists, Projects, Notes, Attachments…
To export Lotus Notes to Outlook PST or Exchange and Domino Server files to Exchange Server or PST files with ease, go for Kernel for Lotus Notes to Outlook conversion tool. Through the video, you can watch the conversion process. A common user with…

606 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