Solved

Ado error with

Posted on 2011-03-24
4
328 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
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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
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…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

828 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