Doe Jowns Doe Jowns - 25 days ago 7
C# Question

Invalid column error in SQL Server using "Where" condition

I'm doing a small program in C#, and I get the "invalid column name" error using the

reader
, although my column name exists. I looked for previous answers on StackOverflow, but didn't really understand the answers given.. Can someone explains me :


  • Why it bugs ?

  • How to solve this problem ?



Here is my code.

[HttpGet]
[Route("IP/{Station=0}/{Timestp=0}")]
public ActionResult IP(int station, string timestp)
{
timestp = timestp.Replace("_", ":");
SqlConnection myConn = new SqlConnection(@"Server=(LocalDb)\MSSqlLocalDB;Integrated security=SSPI;database=Serene7_Default_v1");
List<string> listeIps = new List<string>();

string listDb = string.Format("SELECT DISTINCT IdSource FROM [Serene5_Default_v1].[tcpdump].[TCPDump] WHERE Station = '{0}' AND TimeStp = '{1}';",station,timestp);
SqlCommand myCommand = new SqlCommand(listDb, myConn);
string listDb2 = string.Format("SELECT DISTINCT IdSource,IdDestination FROM [Serene5_Default_v1].[tcpdump].[TCPDump] WHERE Station = {0} AND TimeStp = '{1}';", station, timestp);
SqlCommand myCommand2 = new SqlCommand(listDb2, myConn);
myConn.Open();

SqlCommand cmd = new SqlCommand("SELECT * FROM Serene7_Default_v1.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TCPDump';", myConn);
//opens connection
SqlDataReader reader5 = cmd.ExecuteReader();

while (reader5.Read())
{
System.Diagnostics.Debug.WriteLine(reader5[3]);

// read 'name' column
}
reader5.Close();
SqlDataReader reader = myCommand.ExecuteReader();
while (reader.Read())
{
listeIps.Add(reader[0].ToString());
}

reader.Close();
// some stuff
return View(MVC.Views.Common.Dashboard.DashboardIndex, dashboard);
}


The
reader5
returns :

IdTransmission
TimeStp
IdSource
IdDestination
PortSource
PortDestination
Protocol
ToTheRight
ToTheLeft
Station


and the error is :
Invalid column name 'Station'

Answer Source

Select query runs on [Serene5_Default_v1] DB, but you list table columns from [Serene7_Default_v1] DB. The table's schema in this two different DB equal?