1

I have asked how to use the 'IN' here.

So far, this SQL Server query:

select * 
  from table 
  where column1 in 
    (
        select column2 
        from table
    )

can be translated as:

table.Select(
    string.Format("column1 in ({0})",
    string.Join(",", table Rows.OfType<DataRow>()
        .Select(r=>r["column2"].ToString())
        .Distinct())));

My question is how to translate this SQL query:

select column3
  from table
  where column1 in 
    (
        select column2
        from table
    )

So that I can use what's inside on column3 on another 'IN'.

(e.g.)

select columnA
  from table2 
  where columnB in 
    (
        select column3 
        from table1 
        where column1 in 
            (
                select column2 
                from table1
            )
    )
Community
  • 1
  • 1
Gerald Torres
  • 403
  • 6
  • 18

1 Answers1

0

Linq is a tool. It has its strengths and its limitations.

What I would do is use a custom query to accomplish this. Let SQL Server do the brunt work here, not Linq. It'll dramatically improve the performace, as well.

var sqlTxt = "select columnA "  +
    "from table2 "  +
    "where columnB in "  +
    "( select column3 "  +
    " from table1 "  +
    " where column1 in " +
        "(select column2 " + 
            "from table1) " +
    ")"

results = ExecuteQuery(sqlTxt);
Richard
  • 6,215
  • 4
  • 33
  • 48
  • why the horrible string building instead or a string literal? – Manatherin Aug 23 '11 at 14:39
  • (1) The compiler [simplifies this to a string literal](http://www.yoda.arachsys.com/csharp/stringbuilder.html), applied directly to the variable. (2) doing this allows you to concatenate to it, format it, etc. (3) This isn't meant to be optimal C# code. Just an example of how to fix Linq. – Richard Aug 23 '11 at 14:48
  • @Richard, In other words, I should directly do this in the database. I can't since the data in the DataTable is **not** in the Database. This is what should happen: put all data from a database table to a DataTable() (done that), the user change the items in the DataTable, and when saving the data from the DataTable to another table in the database, the DataTable must be validated first before doing so. The SQL commands above are only an example for what I need to do with my DataTable. – Gerald Torres Aug 24 '11 at 01:41