-1

I have a difficult SQL query, and I don't want to rewrite it on Linq. The problem is: I have two equal tables and I must use one of them in depending on the some condition. So, to pass parameter (the name of table) I use this:

List<Variables> lst = db.Database
    .SqlQuery<Variables>(s, new SqlParameter("tableSource", sourceTable))
    .ToList();

And My query like this:

SELECT @tableSource.PlanId,
   @tableSource.PlanSmall AS PlanImg,
   @tableSource.NOb,
...

It Doesn't works, could someone help me, please?

DavidG
  • 113,891
  • 12
  • 217
  • 223
  • What is `s`...? – Patrick Hofman Apr 03 '18 at 10:34
  • 2
    Please don't do this, you'll only have problems. Instead use your ORM properly otherwise you're opening yourself up to SQL injection attacks. – DavidG Apr 03 '18 at 10:34
  • 1
    If you have two tables with identical structures, it's usually an indication that your data modelling has gone wrong. Often, you'll find that some piece of *data* has instead been placed in the *metadata*, specifically in the names of the tables. If you can correct it (back to a single table with one or more additional columns to contain the misplaced data) you'll find *many* queries fall out far more naturally rather than trying to parameterize the table name. – Damien_The_Unbeliever Apr 03 '18 at 10:37
  • Possible duplicate of [MySQL table name as parameter](https://stackoverflow.com/questions/33254721/mysql-table-name-as-parameter) – PaulF Apr 03 '18 at 10:39
  • I need not injection, you exaggerate, I don't pass name of table through get or post. – Julia Kolesnikova Apr 03 '18 at 10:40

1 Answers1

0

You can't use SqlParameter for this. It is meant to be used to set values for parameters in WHERE clauses for instance. You may consider using a construct like

if (someParam.Equals("thisValue")
{
  return "SELECT * FROM thisTable";
} else if (someParam.Equals("thatValue")
{ 
  return "SELECT * FROM thatTable"; 
}
Hintham
  • 1,078
  • 10
  • 29