.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Forum >> C# >> Post New QuestionBookmark and Share Subscribe to Forum

Passing table name as Parameter in SQL

Posted By: jokertin92     Posted Date: April 24, 2010    Points:2   Category :C#
Hi,
I would like to retrieve data from a table, where the table has to be taken dynamically. How can I get this, can any one guide me?

I tried the following
private void filldatagrid()
{
using (conn = new SqlConnection(Helper.ConnectionString))
{
logfrm = new Login();
comm = new SqlCommand("SELECT * FROM"+@Location",conn);
comm.Parameters.AddWithValue("@Location", logfrm._location);
da = new SqlDataAdapter(comm);
ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}

But shows "Incorrect Syntax near from+@location"

Responses
Author: Kirtan             
Posted Date: April 24, 2010     Points: 5   

private void filldatagrid()
{
using (conn = new SqlConnection(Helper.ConnectionString))
{
logfrm = new Login();
comm = new SqlCommand("SELECT * FROM " +@Location",conn);
comm.Parameters.AddWithValue("@Location", logfrm._location);
da = new SqlDataAdapter(comm);
ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}

Space was Not Given After the From KeyWord in Query now it will work correctly

Author: jokertin92             
Posted Date: April 24, 2010     Points: 5   

No it's not working. It says "Must declare the table variable "@Location"

Author: Kirtan             
Posted Date: April 24, 2010     Points: 5   

private void filldatagrid()
{
using (conn = new SqlConnection(Helper.ConnectionString))
{
logfrm = new Login();
comm = new SqlCommand("SELECT * FROM @Location" ,conn);
comm.Parameters.AddWithValue("@Location", logfrm._location);
da = new SqlDataAdapter(comm);
ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}

Try This!!one there were "" double quote also that was causing problem in query


Author: jokertin92             
Posted Date: April 24, 2010     Points: 5   

Dude!... It doesn't work.... I am struggling.



Post Reply

You must Sign In To post reply
 
 
Find more Forum Questions on C#, ASP.Net, Vb.Net, SQL Server and more Here
Quick Links For Forum Categories:
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  OOPs  SilverlightIISJQuery
JavaScript/VBScriptBiztalkWPFPatten/PracticesWCFOthers
www.DotNetSpark.comUnAnsweredAll

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend