0

Old SQL:

SELECT 
    [FileName], [FilePath] 
FROM 
    dbo.[tb_CrawlData] cr  
WHERE 
    cr.Content LIKE '%' + (SELECT content 
                           FROM [tb_CrawlData]
                           WHERE Content LIKE '%test1%') + '%' 
GROUP BY 
    cr.FileName, [FilePath] 
ORDER BY 
    cr.FileName 

Old C# SQL query:

Sqlquery = "SELECT [FileName], [FilePath]"
                + " FROM [tb_CrawlData] cr "
                + " WHERE cr.Content like '%' + (" + Sqlquery.Substring(Sqlquery.IndexOf(" SELECT") + 1) + ") + '%' ";     
        Sqlquery += " GROUP BY cr.FileName,[FilePath]"
                  + " ORDER BY cr.FileName ";

New SQL:

select 
    [FileName], [FilePath]
from 
    dbo.[tb_CrawlData] cr
where exists (select 1
              from [tb_CrawlData] cd
              where cd.Content like '%data%'
                and cr.Content like '%' + cd.Content + '%')
group by 
    cr.FileName, [FilePath]
order by 
    count(*) desc, cr.FileName

New C# SQL query:

The new sql, I am not so sure how to modify for c#.

2
  • 7
    sorry, you have a working pattern for it in your post - where is the exact problem? do you know how to create strings in c#?`if yes, you can create your sql query. but read about parameterized queries, your sample is very dangerous - its vulnerable to sql injection. Commented Feb 11, 2017 at 7:12
  • This is complicated case meaning subquery exists inside a query involving 2 SQL Table. You'd better to write basic query first.. Commented Feb 11, 2017 at 7:36

2 Answers 2

1

We have to use the SqlCommand class.

string sql = "select 
    [FileName], [FilePath]
from 
    dbo.[tb_CrawlData] cr
where exists (select 1
              from [tb_CrawlData] cd
              where cd.Content like '%data%'
                and cr.Content like '%' + cd.Content + '%')
group by 
    cr.FileName, [FilePath]
order by 
    count(*) desc, cr.FileName"
string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;User Id=sa;Password=2BeChanged!;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(sql, connection);
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
}
Sign up to request clarification or add additional context in comments.

Comments

0

Use QueryFirst. You can run your SQL directly in your C# application.

disclaimer : which I wrote :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.