如何将变量(别名)传递到条件SQL的位置

时间:2016-09-13 02:02:25

标签: c# sql-server

大家好日子,

我希望传递'合并(MDT.DeptName,DD5.Name)为离开名称'到哪里条件。现在错误显示无效列。有可能吗? 下面是我的代码:

SELECT op_id, 
       DD.NAME                                                    Unit, 
       DD1.NAME                                                   Freq, 
       DD2.NAME                                                   Calc, 
       COALESCE(MDT.deptname, DD5.NAME)                           AS departname, 
       COALESCE(CO.yearlytarget + ' ' + dd3.NAME, CO.yearlytarget)AS 
       YearlyTarget, 
       CO.pastyearresult, 
       CO.weight, 
       CO.project, 
       CO.description, 
       Co.datecreated, 
       MDT.weightvalue 
FROM   [MBO].[dbo].[m_newcaloprt] CO 
       LEFT JOIN [MBO].[dbo].[m_ddl] DD 
              ON CO.unit_ddl = DD.d_id 
       LEFT JOIN [MBO].[dbo].[m_ddl] DD1 
              ON CO.freq_ddl = DD1.d_id 
       LEFT JOIN [MBO].[dbo].[m_ddl] DD2 
              ON CO.calc_ddl = DD2.d_id 
       LEFT JOIN [MBO].[dbo].[m_user] US 
              ON CO.uid = US.id 
       LEFT JOIN [MBO].[dbo].[m_user] US1 
              ON US1.deptid = US.deptid 
       LEFT JOIN [MBO].[dbo].[m_ddl] DD5 
              ON US1.deptid = DD5.d_id 
       LEFT JOIN [MBO].[dbo].[m_multipledept] MDT 
              ON MDT.projectid = CO.op_id 
       LEFT JOIN [MBO].[dbo].[m_ddl] DD3 
              ON CO.calcsymbol = DD3.d_id 
WHERE  departname = '' 
       AND isactive = 0 
       AND isverifed = 1 

我希望将此代码用于C#。请指教

1 个答案:

答案 0 :(得分:4)

您不能在Alias子句中使用Where名称。使用原始列

WHERE  COALESCE(MDT.deptname, DD5.NAME) = '' 
       AND isactive = 0 
       AND isverifed = 1 

这是逻辑处理查询的方式

1. FROM
2. ON
3. OUTER
4. WHERE --here
5. GROUP BY
6. CUBE | ROLLUP
7. HAVING
8. SELECT --here
9. DISTINCT
10 ORDER BY
11. TOP

由于在Where之前处理Select子句,我们在Alias子句中不会有Where个名称