Inner Join In SqlQuery Giving Error - sql

I am trying to perform this query :
List<string> info = db.Database.SqlQuery<string>("
SELECT u.Name, a.LName
FROM dbo.Table1 u
INNER JOIN dbo.Table2 a ON a.Table1id = u.id
WHERE u.Name = '" + name + "'").ToList();
When I try and do that query I get this error:
The data reader has more than one field. Multiple fields are not valid
for EDM primitive or enumeration types.
When I just tried to select the Name without the inner join it worked fine so how do I fix that so that I can perform my inner join without errors?
Thanks!

What #xdd said worked well
List<string> info = db.Database.SqlQuery<string>("
SELECT u.Name + a.LName
FROM dbo.Table1 u
INNER JOIN dbo.Table2 a ON a.Table1id = u.id
WHERE u.Name = '" + name + "'").ToList();
Fixed that

Related

SQL to LINQ to SQL expression without Join

While converting an SQL query below query with navigation in Entity Framework
SELECT DISTINCT
a.ApplicationID, eA.EmployeeID AS AppID, eA.EmailID AS AppEmail,
eA.Title + eA.Name AS Applicant, eR.EmployeeID, eR.Title + eR.Name
AS Employee, eR.EmailID AS Email, r.Title AS Role, r.RoleID, t .Title AS
Task, t .TaskID, d .ShortName AS AppDeptSN, a.Reminders, '' AS SubTaskID
FROM
dbo.Application_TaskLog AS a INNER JOIN
dbo.Task AS t ON t .TaskID = a.TaskID INNER JOIN
dbo.Role AS r ON r.RoleID = t .RoleID INNER JOIN
dbo.Application_Role AS ar ON ar.ApplicationID = a.ApplicationID AND
ar.RoleID = t .RoleID INNER JOIN
dbo.Employee AS eR ON eR.EmployeeID = ar.EmployeeID INNER JOIN
dbo.Application AS app ON app.ApplicationID = a.ApplicationID INNER JOIN
dbo.Employee AS eA ON eA.EmployeeID = app.EmployeeID LEFT OUTER JOIN
dbo.Departments AS d ON eA.DepartmentID = d .DepartmentID
I wrote the following function to populate gridview
public List<Application_TaskLog> GetAppTaskLogDistinct(int appID)
{
var context = new FPSDB_newEntities();
var data = (from atl in context.Application_TaskLog
where atl.ApplicationID == appID
&& !atl.Application.ApplicationClosed && !atl.Completed
select atl).Distinct().ToList();
return data;
}
Distinct() is not working as it works in the SQL. I am confused how to use Distinct as I have used in SQL
context.Application_TaskLog already returns distinct Application_TaskLog records and there's nothing in the query that duplicates them, so Distinct() doesn't make any difference

Optimizing SQL join single column with multiple columns in another table

I have two tables.
common_products
id
product
owner_uid
backup_uid
manager_uid
ss_users
userID
firstName
lastName
email
I want to get a name/email list of all the owners, backups and managers.
I am using the query below, but was wondering if there was a more efficient way to go about querying the tables.
WORKING QUERY:
SELECT DISTINCT email,
( firstName + ' ' + lastName ) AS userFull,
lastName
FROM common_products cp
LEFT OUTER JOIN ss_users u
ON u.userID = cp.owner_uid
UNION
SELECT DISTINCT email,
( firstName + ' ' + lastName ) AS userFull,
lastName
FROM common_products cp
LEFT OUTER JOIN ss_users u
ON u.userID = cp.backup_uid
UNION
SELECT DISTINCT email,
( firstName + ' ' + lastName ) AS userFull,
lastName
FROM common_products cp
LEFT OUTER JOIN ss_users u
ON u.userID = cp.manager_uid
Is there a more optimized way to query the database?
I suspect that this version might be faster:
select u.email, (u.firstName+ ' '+u.lastName) AS userFull, u.lastName
from ss_users u
where exists (select 1 from common_products cp where u.userID = cp.owner_uid) or
exists (select 1 from common_products cp where u.userID = cp.backup_uid) or
exists (select 1 from common_products cp where u.userID = cp.manager_uid);
Then for best performance add three indexes: common_products(owner_uid), common_products(backup_uid), and common_products(manager_uid).
This will eliminate the duplicate elimination (because you are using union) and the exists should be at least as fast as the joins.
I'm going to simplify it, but the JOIN is the important part. I'll leave it to you to tweak the SELECT part.
SELECT DISTINCT owner.email AS owner_email, backup.email AS back_email, manager.email AS man_email
FROM common_product cp LEFT JOIN ss_users owner on owner.userID = cp.owner_uid
LEFT JOIN ss_users backup on backup.userID = cp.backup_uid
LEFT JOIN ss_users manager on manager.userID = cp.manager_uid
Ensure there are indexes on common_products's owner_uid, backup_uid, and manager_uid fields as well as ss_users's userID field and you could improve performance a bit further by including the columns needed on the index.
SELECT DISTINCT
user_owner.email [OwnerEmail],user_owner.firstName + ' ' + user_owner.lastName [OwnerUserFull], user_owner.lastName [OwnerLastName],
user_backup.email [BackupEmail],user_backup.firstName + ' ' + user_backup.lastName [BackupUserFull], user_backup.lastName [BackupLastName],
user_manager.email [ManagerEmail],user_manager.firstName + ' ' + user_manager.lastName [ManagerUserFull], user_manager.lastName [ManagerLastName]
FROM common_products cp
LEFT OUTER JOIN ss_users user_owner ON user_owner.userID = cp.owner_uid
LEFT OUTER JOIN ss_users user_backup ON user_backup.userID = cp.backup_uid
LEFT OUTER JOIN ss_users user_manager ON user_manager.userID = cp.manager_uid
It's been a while since I've practised by SQL fu, but I think this should work:
SELECT DISTINCT email,
(firstName+ ' '+lastName) AS userFull,
lastName
FROM common_products cp
INNER JOIN ss_users u
ON (u.userID = cp.owner_uid OR u.userID = cp.backup_uid OR u.userID = cp.manager_uid)

How to Get All Rows matched + Unmatched and Unmatched Rows Column Will be null

I am working on an university management system. This is my database diagram
Database Diagram
I am creating a search form using this query:
SELECT Distinct
TblStudentBioData.RegNo,
TblStudentBioData.First_NameUr + SPACE(1)+ TblStudentBioData.Middle_NameUr + SPACE(1) + TblStudentBioData.Last_NameUr AS Name,
TblStudentBioData.Father_NameUr,
Ay.AcademicYearName,
Smst.SemName,
TBLCOLLEGE.CollegeName,
CID.ClassName,
TblImages.Images,
TblStudentBioData.Student_ID,
TblImages.ImageId,
Ay.AcademicYearId,
Smst.SemesterId,
TblClassSchedule.ClassSchId
FROM
TblStudentBioData
LEFT JOIN
TblStudentDetail ON (TblStudentBioData.Student_ID = TblStudentDetail.Student_ID)
OR (TblStudentBioData.Student_ID != TblStudentDetail.Student_ID)
INNER JOIN
TBLCFGSEX AS sex ON TblStudentBioData.CfgSexId = sex.CfgSexId
INNER JOIN
TBLMARITALSTATUS ON TblStudentBioData.MaritalStatusId = TBLMARITALSTATUS.MaritalStatusId
INNER JOIN
TblStudentSubAss ON TblStudentDetail.StudentDetailID = TblStudentSubAss.StudentDetailID
INNER JOIN
TblSubAss ON TblSubAss.SubAssId = TblStudentSubAss.SubAssId
INNER JOIN
TblClassSchedule ON TblStudentDetail.ClassSchId = TblClassSchedule.ClassSchID
INNER JOIN
TableClass AS CID ON TblClassSchedule.ClassID = CID.ClassID
INNER JOIN
TblImages ON TblStudentBioData.ImageId = TblImages.ImageId
LEFT JOIN
TBLCOLLEGE ON CID.CollegeId = TBLCOLLEGE.CollegeID
INNER JOIN
TBLBLOODGROUP BG On TblStudentBioData.BloodID = BG.BloodId
INNER JOIN
tableSemAssigning SA On TblClassSchedule.SemAssId = Sa.SemAssId
INNER JOIN
TblAcademicYear AY On SA.AcademicYearId = AY.AcademicYearId
INNER JOIN
TableSemester Smst On Smst.SemesterId = Sa.SemesterId
and this query gives me the output like this
In the result the 5th row is not matching row.
My question: how to show null value in non matching row's columns which I mention in the image?
As far as I can tell it would be like this. Anything that relates directly to TblStudentBioData MIGHT be an an INNER JOIN (I cannot tell) but everything that relates to TblStudentDetail should be a left join.
Also be careful with any where clause that you don't override these left joins.
SELECT DISTINCT /* I hate distinct, there is probably a better way */
TblStudentBioData.RegNo
, TblStudentBioData.First_NameUr + SPACE(1) + TblStudentBioData.Middle_NameUr + SPACE(1) + TblStudentBioData.Last_NameUr AS Name
, TblStudentBioData.Father_NameUr
, Ay.AcademicYearName
, Smst.SemName
, TBLCOLLEGE.CollegeName
, CID.ClassName
, TblImages.Images
, TblStudentBioData.Student_ID
, TblImages.ImageId
, Ay.AcademicYearId
, Smst.SemesterId
, TblClassSchedule.ClassSchId
FROM TblStudentBioData
INNER JOIN TBLCFGSEX AS sex
ON TblStudentBioData.CfgSexId = sex.CfgSexId
INNER JOIN TBLMARITALSTATUS
ON TblStudentBioData.MaritalStatusId = TBLMARITALSTATUS.MaritalStatusId
INNER JOIN TblImages
ON TblStudentBioData.ImageId = TblImages.ImageId
INNER JOIN TBLBLOODGROUP BG
ON TblStudentBioData.BloodID = BG.BloodId
LEFT JOIN TblStudentDetail
ON (TblStudentBioData.Student_ID = TblStudentDetail.Student_ID)
LEFT JOIN TblStudentSubAss
ON TblStudentDetail.StudentDetailID = TblStudentSubAss.StudentDetailID
LEFT JOIN TblClassSchedule
ON TblStudentDetail.ClassSchId = TblClassSchedule.ClassSchID
LEFT JOIN TblSubAss
ON TblSubAss.SubAssId = TblStudentSubAss.SubAssId
LEFT JOIN TableClass AS CID
ON TblClassSchedule.ClassID = CID.ClassID
LEFT JOIN TBLCOLLEGE
ON CID.CollegeId = TBLCOLLEGE.CollegeID
LEFT JOIN tableSemAssigning SA
ON TblClassSchedule.SemAssId = SA.SemAssId
LEFT JOIN TblAcademicYear AY
ON SA.AcademicYearId = AY.AcademicYearId
LEFT JOIN TableSemester Smst
ON Smst.SemesterId = SA.SemesterId

SQL join query result issue

I have two tables one is Friends table and other table is user profile table (all user related information e.g. firstname, lastname etc) both has relation among them
Friend table (It has two entries for every user for e.g. the first two rows)
Now i want to display names of users from above table which will look like below
so in the output i want to remove duplicates which is not working for me
my query
select distinct u.FirstName + ' ' + u.LastName As UserName,
(select distinct firstname + ' ' + lastname from UserProfiles where id = uw.friendid) as FriendName
from UserFriends as uw left join userprofiles as u
on u.id = uw.userid
You need to join UserProfiles twice on UserFriends since there are two columns are dependent on it.
SELECT a.ID,
f.FirstName + ' ' + f.LastName FriendName,
u.FirstName + ' ' + u.LastName UserName
FROM UserFriends a
INNER JOIN UserProfiles f
ON a.FriendID = f.ID
INNER JOIN UserProfiles u
ON a.UserID = u.ID
INNER JOIN UserFriends dup
ON a.FriendID = dup.UserID
AND dup.FriendID = a.UserID
AND a.ID > dup.ID
SQLFiddle Demo
I would suggest that you have to use CTE to eliminate the duplicates from the beggining(that can be done by self joining the table). I have managed to reproduce your scenario, so if you adjust the query a bit, you will be able to obtain the desired result
with cte as
(select
t1.id as a_id
,t1.friendID as a_friendID
,t1.userID as a_userID
,t2.id as b_id
,t2.friendID as b_friendID
,t2.userID as b_userID
from #temp t1
left join #user t2 on t1.id+1=t2.id
),
cte2 as
select
a_id
,a_userID
,a_friendID
from cte t1
where a_friendID = (select b_friendID from cte t2 where t2.b_id= t1.b_id-1)
)
select firstname+ ' '+lastname as FriendName
,firstname+ ' '+lastname as UserName
from cte2 uw
left join UserProfiles u on uw.a_userID=u.ID and uw.a_friendID=u.id

MS Access query problem

SELECT
tbl_vehicle_models.model_name AS Vehicle_Model,
tbl_vehicle_models.manufacturer AS Manufacturer,
tbl_jobs.vehicle_registration_number AS Registration_Number,
tbl_customers.first_name + " " + tbl_customers.last_name AS Customer_Name,
tbl_customers.address AS Address,
tbl_customers.contact_no AS Contact_Number,
tbl_jobs.cost_charged AS Cost,
tbl_jobs.was_accident AS Was_Accident,
tbl_jobs.was_towed AS Was_Towed,
tbl_jobs.job_call_time AS Call_Time,
tbl_jobs.job_arrival_time AS Arrival_Time,
tbl_jobs.job_leaving_scene_time AS Leaving_Time,
tbl_places.place_name AS Place
FROM
tbl_jobs
INNER JOIN tbl_vehicle_models
ON ( tbl_vehicle_models.ID = tbl_jobs.vehicle_model )
INNER JOIN tbl_customers
ON ( tbl_customers.ID = tbl_jobs.customer_id )
INNER JOIN tbl_places
ON ( tbl_places.ID = tbl_jobs.job_place )
What's wrong with this query? I am getting error saying missing operator in query expression '( v.ID = j.vehicle_model )
INNER JOIN tbl_customers c ON ( c.id = j.customer_id )
INNER JOIN tbl_places p ON ( p.ID = j.job_place'
Edit: This solved my problem:
SELECT tbl_vehicle_models.model_name, tbl_vehicle_models.manufacturer, tbl_jobs.vehicle_registration_number, tbl_customers.first_name & " " & tbl_customers.last_name AS Expr1, tbl_customers.address, tbl_customers.contact_no, tbl_jobs.cost_charged, tbl_jobs.was_accident, tbl_jobs.was_towed, tbl_jobs.job_call_time, tbl_jobs.job_arrival_time, tbl_jobs.job_leaving_scene_time, tbl_places.place_name
FROM ((tbl_jobs INNER JOIN tbl_vehicle_models ON tbl_jobs.vehicle_model = tbl_vehicle_models.ID) INNER JOIN tbl_customers ON tbl_jobs.customer_id = tbl_customers.ID) INNER JOIN tbl_places ON tbl_jobs.job_place = tbl_places.ID;
Are you sure that v.ID and j.vehicle_model have the same data type?
Looks like v.ID is an integer and j.vehicle_model a string
I think this problem happens when you try to use operators with incompatible operand data types.
EDIT:
Then, try changing
c.first_name + " " + c.last_name
to
c.first_name & " " & c.last_name
I think that's a problem with this concatenation
This solved my problem:
SELECT tbl_vehicle_models.model_name, tbl_vehicle_models.manufacturer,
tbl_jobs.vehicle_registration_number, tbl_customers.first_name & " " &
tbl_customers.last_name AS Expr1, tbl_customers.address, tbl_customers.contact_no,
tbl_jobs.cost_charged, tbl_jobs.was_accident, tbl_jobs.was_towed, tbl_jobs.job_call_time,
tbl_jobs.job_arrival_time, tbl_jobs.job_leaving_scene_time, tbl_places.place_name
FROM ((tbl_jobs
INNER JOIN tbl_vehicle_models ON tbl_jobs.vehicle_model = tbl_vehicle_models.ID)
INNER JOIN tbl_customers ON tbl_jobs.customer_id = tbl_customers.ID)
INNER JOIN tbl_places ON tbl_jobs.job_place = tbl_places.ID;