I am trying to get my linq query to replicate my t-sql but I am lost.
SELECT *
FROM BaiDetail INNER JOIN
BaiDetailMap ON BaiDetail.DetailText
LIKE '%' + BaiDetailMap.BaiDetailMapSearchText +'%'
This is what I have so far... but no go
from det in Source
from map in Map
where det.DetailText.Contains(map.SearchText)
select new {det, map}
Error Message:
Only arguments that can be evaluated on the client are supported for the String.Contains method.
from det in Source
from map in Map
where SqlMethods.Like(map.DetailText, "%" + map.SearchText + "%"))
select new {det, map}
Related
I am trying to create an update query in SQLKata that includes a 'FromRaw' statement. Below is a copy of my best attempt at what I am trying to accomplish. I have to use a FromRaw statement because I am linking 2 tables on an evaluation. Is there any way to accomplish this without having to resort to the Statement() function?
var query = db.Query(Table1)
.FromRaw(" Table1 INNER JOIN Table2 " +
" ON LEFT([Table1].[Company],5) = " +
" LEFT([Table2].[Company],5)" )
.Update(new { scrub = "match" });
Below is a copy of the error message:
System.InvalidOperationException: 'Invalid table expression'
This bit of code works just fine for me:
var compiler = new SqlServerCompiler();
//var Table1 = "Table1";
var query = new Query(null)
.FromRaw("Table1 INNER JOIN Table2 " +
"ON LEFT([Table1].[Company],5) = " +
"LEFT([Table2].[Company],5)")
.AsUpdate(new { scrub = "match" });
var rawSql = compiler.Compile(query).RawSql;
With rawSql value being:
UPDATE Table1 INNER JOIN Table2 ON LEFT([Table1].[Company],5) = LEFT([Table2].[Company],5) SET [scrub] = ?
The error message you're getting is only found in Compiler.cs, which is why I suggested that you check which compiler you're using.
I was trying to replace SQL code with LINQ in order to migrate in to MVC ,but i don't know how to use subquery in LINQ.As of now i have replaced inner sql query with LINQ,i would like to know how to do with outer query.
Following is the SQL query
SELECT
DISTINCT GP_REGION.REGION_MAIN Region_Code,
R1.REGION_NAME
FROM
GP_REGION
INNER JOIN GP_REGION R1 ON GP_REGION.REGION_MAIN = R1.REGION_CODE
WHERE
GP_REGION.REGION_HAS_DATA = 'Y'
AND
GP_REGION.REGION_MAIN IN
(
SELECT
DISTINCT AR.BRANCH_CODE
FROM
PORTAL.UA_APPLN_ROLE AR
INNER JOIN PORTAL.UA_GROUP G ON AR.GROUP_CODE = G.GROUP_CODE
WHERE
G.USER_ID = '" + Global.UserId() + "' AND AR.APPLICATION_ID = '" + ApplicationId + "'
)
ORDER BY
GP_REGION.REGION_MAIN
Here the inner query i have replaced as shown below by using following LINQ
var regions = from p in db3.UA_APPLN_ROLE.AsEnumerable()
join i in db3.UA_GROUP.AsEnumerable()
on p.GROUP_CODE equals i.GROUP_CODE
where
i.USER_ID == Global.UserId()
&&
p.APPLICATION_ID == ConfigurationManager.AppSettings["ApplicationId"]
select new
{
branchcode = p.BRANCH_CODE
};
But i would like to know the outer sql query how can i replace and join with existing LINQ code i wrote
You combine the subquery into the main query as follows:
var efQuery = from gp in db3.GP_REGION
join r1 in db3.GP_REGION on gp.REGION_MAIN equals r1.REGION_CODE
where regions.Contains(gp.REGION_MAIN)
&& gp.REGION_HAS_DATA = "Y"
select new
{
Region_Code = gp.REGION_MAIN,
Region_Name = r1.REGION_NAME
};
var queryResult = efQuery.Distinct().OrderBy(x => x.Region_Code);
You can speed the processing up a bit by using .AsNoTracking(), e.g. db3.GP_REGION.AsNoTracking().
In general it's a good idea to monitor the generated SQL query to avoid situations where it looks simple in code, but is transformed into bad SQL.
But in my opinion the advantages of having the query a first class member in your code (compared to SQL in strings) outweigh the sometimes non-intuitive generated SQL.
I have the following query
SELECT dictionaryEncryptedIndex, filelocation FROM `DictionaryTable`
WHERE `dictionaryEncryptedWord` LIKE '0x0E6E'";
In c# I loop over the results from the above query and for every loop iteration I use the following query to get my end results:
SELECT * FROM `MaskedIndexTable`
WHERE `maskedIndexEncryptedIndex`
LIKE '" + dictionaryEncryptedIndexFROMABOVEQUERY + "'
AND `fileLocation` = '" + filelocationFROMABOVEQUERY + "'";
The relation between dictionaryEncryptedIndex and maskedIndexEncryptedIndex is not a one on one relation.
Does anyone know how to do the above in one SQL query that can be used in Microsoft Access?
I've tried multiple things like:
SELECT * from DictionaryTable, MaskedIndexTable
WHERE MaskedIndexTable.maskedIndexEncryptedIndex = DictionaryTable.dictionaryEncryptedIndex
AND MaskedIndexTable.fileLocation =DictionaryTable.fileLocation
AND `dictionaryEncryptedWord` LIKE '0x0E6E'
SELECT dictionaryEncryptedWord, DictionaryTable.filelocation
FROM DictionaryTable
INNER JOIN MaskedIndexTable
ON (MaskedIndexTable.maskedIndexEncryptedIndex =DictionaryTable.dictionaryEncryptedIndex )
WHERE `dictionaryEncryptedWord` LIKE '...'
SELECT distinct *
FROM MaskedIndexTable
INNER JOIN DictionaryTable
ON (MaskedIndexTable.maskedIndexEncryptedIndex = DictionaryTable.dictionaryEncryptedIndex )
WHERE MaskedIndexTable.Id IN
(
SELECT DictionaryTable.Id
FROM DictionaryTable
WHERE `dictionaryEncryptedWord` LIKE '..')
AND `dictionaryEncryptedWord` LIKE '...'
but none of them seem to produce the correct results (the results I get with my c# code)
You will need to change this if you want to use a wildcard in your LIKE criteria.
First create a query in Access similar to your first one called encryptedWordsQuery
SELECT DictionaryTable.dictionaryEncryptedIndex, DictionaryTable.fileLocation
FROM DictionaryTable
WHERE (((DictionaryTable.dictionaryEncryptedWord) Like "0x0E6E"));
Second create a query in Access as follows:
SELECT MaskedIndexTable.maskedIndex, MaskedIndexTable.maskedIndexEncryptedIndex, MaskedIndexTable.fileLocation
FROM MaskedIndexTable
WHERE Exists (SELECT *
FROM encryptedWordsQuery
WHERE MaskedIndexTable.maskedIndexEncryptedIndex = encryptedWordsQuery.dictionaryEncryptedIndex
AND MaskedIndexTable.fileLocation = encryptedWordsQuery.FileLocation);
I find it easier to create two separate queries rather than just one in Access.
I think this should work--if you are able to post sample data we could make a SQLFiddle to demo it.
SELECT dt.dictionaryEncryptedIndex, dt.filelocation
FROM DictionaryTable dt
INNER JOIN MaskedIndexTable mit
ON mit.fileLocation = dt.fileLocation
AND mit.maskedIndexEncryptedIndex = dt.dictionaryEncryptedIndex
WHERE dt.dictionaryEncryptedWord LIKE '0x0E6E*'
string sqlQueryString = " SELECT g.code AS GoodCode, g.name AS GoodName, " +
"msr.name AS MsrName, sm.min_quan AS KolMin, sm.max_quan AS KolMax, " +
"sm.quan AS KolNal, ord.prc AS EdPrice, s.name AS Sklad, m.name AS Mol, " +
"k.code AS KodDost, k.name AS NameDost " +
"FROM N_GOODS_{0} AS g INNER JOIN " +
"G_SMGS_{0} AS sm ON g.id = sm.good_id INNER JOIN " +
"N_KNTRS_{0} AS k ON g.id = k.id INNER JOIN " +
"N_PRC_LISTS_{0} AS pr ON g.id = pr.id INNER JOIN " +
"G_ORDD_{0} AS ord ON sm.smg_id = ord.smg_id INNER JOIN " +
"N_MOLS_{0} AS m ON sm.mol_id = m.id INNER JOIN " +
"N_STORS_{0} AS s ON sm.stor_id = s.id INNER JOIN " +
"N_MSRS_{0} AS msr ON g.id = m.id";
sqlQueryString = String.Format(sqlQueryString, dbLink.CurrentFirm.Id);
return " ( " + sqlQueryString + " ) AS t";
This is the string for an sql query, that I am trying to do in a piece of c# code. However I lost my whole day trying to make it work. This is the error that I get :
Incorrect syntax near the keyword 'FROM'.
Incorrect syntax near the keyword 'AS'.
Try:
return "SELECT * FROM ( " + sqlQueryString + " ) AS t";
Additionally you should try setting a breakpoint on your return statement. Get the value of sqlQueryString there and try running it directly in SQL Server Management Studio.
First, this probably isn't a C# question except to say that you should likely learn the...
string strSql = #"SELECT *
FROM TABLE";
syntax so that 1.) You can do away with all the " + stuff and 2.) You can cut and paste something in from an isql client.
So what you really want to do is...
Debug in your IDE by setting a breakpoint at that last line,
Hover your cursor over sqlQueryString,
Right-click sqlQueryString in the "floater" that appears (I put my mouse over strReturn, the floater comes up. Right click the strReturn that appears floating above -- blue rectangle is what you want)
Select the option to copy the value.
Paste your clipboard with sqlQueryString's contents into Notepad, gvim, whatever.
Let us know what that says.
Then tell us precisely what happens when you run that statement directly against the database.
You might also give us some idea of what you expected to happen [based on having run the original query against the database earlier, perhaps].
And then accept that even the best of us occasionally lose an hour or two doing something dumb with SQL. ;^) With the above information, however, we could probably help cut that down a bit.
EDIT: Rather, if, as your comment suggests, the query works when run directly against (MS-SQL Server?), the C# issue potentially comes after this code, when you run it against the database. First do the above and ensure what's in sqlQueryString is what you ran against the db.
EDIT2: Made the debug steps into a bulleted list to make them more obvious. Don't just tell us it work; tell us what was in sqlQueryString. But, again, as with the first edit, if that string is okay, your problem likely occurs later on in your C# code.
Are you immediately throwing against the database? What's that code look like?
Looks like the problem is in the return statement at the end.
( SELECT foo FROM bar ) AS baz; is not a valid SQL statement by itself, it's a fragment.
As #Yuck suggests, try SELECT * FROM ( " + sqlQueryString + " ) AS t"; instead.
i have these sql statement to output job field based on user input.
SELECT jf.name, j.jname, c.cname, cj.url
FROM company_has_job cj
INNER JOIN job j ON j.id = cj.job_id
INNER JOIN company c ON c.id = cj.company_id
INNER JOIN jobfield_has_job jhj ON jhj.job_id = j.id
INNER JOIN jobfield jf ON jf.id = jhj.jobfield_id
WHERE jf.name LIKE '%' + #InputJob + '%'
for example when user input query "Programmer", the system will output all programmer job defined in the database.but the system does not show any result if i enter "Program" in the search box. This is my control parameter:
<SelectParameters>
<asp:ControlParameter ControlID="TextBox4" Name="InputExpertise"
PropertyName="Text"/>
</SelectParameters>
can you tell me where i did wrong? your help is much appreciated.
I am not sure if this is just a typo, but shouldn't it be
WHERE jf.name LIKE '''%' + #InputJob + '%'''
Notice that I made it so that the code will end up as LIKE '%Program%', whereas it looks like it will end up as LIKE %Program% currently.
Can't comment yet, but perhaps this will answer the question, do any of the columns that you join on allow NULLs? The inner join will not return results that include a null.
consider this query:
select wb.employee,wb.Dept from web_user wb
inner join Employee e on wb.Dept = e.Department
where wb.employee like '%Ted%'
No results
but this:
select wb.employee,wb.Dept from web_user wb
left join Employee e on wb.Dept = e.Department
where wb.employee like '%Ted%'
Returns:
Ted NULL
Also it my be helpful to debug, set a breakpoint on the actual call to the database to get the SQL statement it is using and then paste that into a query editor. I've done this many times when a query does not behave. Once you know what the program is using for the SQL statement that may also help you find the issue.