如何将带有case语句SQL的临时表转换为Linq?

时间:2013-06-04 08:35:37

标签: c# sql-server asp.net-mvc linq linq-to-entities

我是Linq的新手,不知道如何在MS SQL查询中解决一些问题。

Select e.EmployeeID
, e.EmployeeName
, e.Division
, e.DepartmentCode
, e.DesignationGrpCode
Into #temp
from chr.dbo.EMPLOYEE e
Where e.DepartmentCode in ( 
                        Select DepartmentCode 
                        from chr.dbo.EMPLOYEE 
                        where EmployeeID = 'S-1287'
                        )

Select * from #temp t
where t.EmployeeID in (
                        Case When t.Division <> 'CHR' Then (Select EmployeeID from #temp where DesignationGrpCode = 'CorpDMGR')
                        Else (Select EmployeeID from #temp where DesignationGrpCode = 'MGT') End)
Drop table #temp

如何将此查询转换为Linq?请

这是我的linq声明

var employee = new Common().Employee();

        var jobdesc = new Common().JobHistory();

        List<EMPLOYEE> dCode = (from e in employee
                              where e.EmployeeID == "S-1204"
                              select new EMPLOYEE
                              {
                                  DepartmentCode = e.DepartmentCode
                              }).ToList();

        List<EMPLOYEE> emp = (from e in employee
           join d in dCode on e.DepartmentCode equals d.DepartmentCode into temp
           from t in temp.DefaultIfEmpty()


           orderby e.EmployeeName
           select new EMPLOYEE
           {
               EmployeeID = e.EmployeeID,
               EmployeeName = e.EmployeeName
           }).ToList();

但是知道如何检查CASE ELSE语句

2 个答案:

答案 0 :(得分:1)

在极端情况下,你可以这样做:

using (var context = new ConnectDb())    
    {
         context.ExecuteStoreCommand("your query");
         // for exaple: context.ExecuteStoreCommand("TRUNCATE TABLE Peoples"); 
         context.SaveChanges();
    }

答案 1 :(得分:1)

给这个人一个机会。它编译并在ideone中运行,但未经测试,所以祝你好运。

var temp = from e in context.EMPLOYEE
           where (from f in context.EMPLOYEE
                  where f.EmployeeID == "S-1287"
                  && e.DepartmentCode == f.DepartmentCode
                  select f).Any()
           select e;

var result = from t in temp
             where (from u in temp
                    where u.DesignationGrpCode
                          == (t.Division == "CHR" ? "CorpDMGR" : "MGT")
                    && t.EmployeeID == u.EmployeeID
                    select u).Any()
             select t;

假设您指向SQL Server 2005或更高版本,我希望LINQ足够聪明,可以将临时表转换为WITH子句。

UPDATE:由于temp的子查询几乎肯定会返回单个值,因此您应该(假设EmployeeID是主键)将其分开:

string deptForS1287 = (from e in context.EMPLOYEE
                       where e.EmployeeID == "S-1287"
                       select DepartmentCode).Single();

var temp = from e in context.EMPLOYEE
           where e.DepartmentCode == deptForS1287
           select e;

⋮

如果EMPLOYEE表没有提到员工S-1287,这会带来抛出异常的附带好处。