How to do the following in SQL, access? - c#

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*'

Related

Simple query for getting max value for each entity

Developing an application in C# using a MySQL database. It involves cows and their weights. When displaying the cows details in a table, I want to display all of the animal's details as well as their last weight.
I have two tables used for this: 'Cattle' and 'Weights'. Each animal has a unique ID and this ID is used as foreign key in weights table along with the date taken and what they weighed. Up to now the way I am doing it is getting the MAX(Date) in the weights table and using a left join however if animal wasn't weighed on that date then it won't be included. I could use each animals MAX(Weight) however some animals may drop in weight due to illness etc.
SELECT Cattle.TagNumber,
Cattle.HerdNumber,
Cattle.Breed,
Cattle.DOB,
Cattle.Group,
Weights.Weight
FROM Cattle
LEFT JOIN Weights ON Cattle.TagNumber = Weights.TagNumber
WHERE Cattle.Group = '" + group + "'
AND Date = '" + date.ToString("yyyy/MM/dd") + "'";
The above query is what I use when filtering the data by the animals group. I understand that I could go through each animal individually and get their MAX(Weight) however this severely hinders the performance.
If you select for the Max(Date) found on the join, instead of searching a specific Date (Where clause), you will always get the results. Not exactly sure if this is what is asked.
SELECT Cattle.TagNumber,
Cattle.HerdNumber,
Cattle.Breed,
Cattle.DOB,
Cattle.Group,
Weights.Weight,
MAX(Date)
FROM Cattle
LEFT JOIN Weights ON Cattle.TagNumber = Weights.TagNumber
WHERE Cattle.Group = '" + group + "'
Group by Cattle.TagNumber;
Edit
The query should also return values with no weights; you just need to filter the data. You can use Case (it might not work exactly as I wrote it, but something around that). There was the End missing; also you probably need to convert weight to a nvarchar (or what you chose), otherwise you will get an error when inserting weight in the column NAMECOLUMN
SELECT Cattle.TagNumber,
Cattle.HerdNumber,
Cattle.Breed,
Cattle.DOB,
Cattle.Group,
(Case when Weights.Weight is null then 'N/A' Else Convert(nvarchar(max),Weights.Weight) End) as NAMECOLUMN,
MAX(Date)
FROM Cattle
LEFT JOIN Weights ON Cattle.TagNumber = Weights.TagNumber
WHERE Cattle.Group = '" + group + "'
Group by Cattle.TagNumber;

Replacing old sql written in asp.net with Linq

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.

SQL Like statement not return a wildcard output asp.net c#

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.

Select highest number from table when number stored as string?

I'm trying to write a windows forms app in C# .Net 4 it connects to a SQL Server 2008 database and I want to Select highest number from a table where the number is stored as string!
string SQL = "select MAX(CONVERT(int, myField)) from myTable where myCode = '" + theCust + "'";
I have also tried Max(CAST(myField as Int)) in the select statement but both fail to return anything even though the Database has for the theCust two rows with 10001 and 10002. The Error i Get is "Enumeration yielded no results"
What am I doing wrong?
I'm using the in built System.Data.SqlClient and if I just do a
string SQL = "select myField from myTable where myCode = '" + theCust + "'";
it returns both numbers as strings. I know I could sort them in code but if the Database gets large that would not be a good approach!
I just tried it again with an int Field in the db and still got the same error! Is Max the wrong thing to be using?
You can try it like this:
SELECT TOP 1 CAST(MyColumn AS int) AS TheMax
FROM MyTable
ORDER BY TheMax DESC
So (using the sloppy method, always paramaterize!)
String sql = "SELECT TOP 1 CAST(MyColumn AS int) AS TheMax FROM MyTable WHERE MyParam = '" + param + "' ORDER BY TheMax Desc";
//Fill DataAdapter/DataReader etc.
Have this function in your database(s):
CREATE FUNCTION dbo.IsAllDigits (#MyString VARCHAR(8000))
RETURNS TABLE AS
RETURN (
SELECT CASE
WHEN #MyString NOT LIKE '%[^0-9]%'
THEN 1
ELSE 0
END AS IsAllDigits
)
because it's better than the in-build ISNUMERIC() in T-SQL.
Then you can use this query to get set of strings that convert to integer types without errors, and filter them like with TOP 1.
SELECT TOP 1 MyColumn AS TheMax
FROM MyTable
WHERE IsAllDigits(MyColumn)=1
ORDER BY MyColumn DESC

How to use Contains() in my join

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}

Categories

Resources