使用别名的SQL查询

时间:2017-04-26 11:58:06

标签: sql sql-server

我曾尝试在MS SQL服务器中编写下面的SQL查询,但它在 WHERE 附近显示语法错误。

Select ECUID,ECUNAME 
FROM 
(SELECT     [ECU-ID] as ECUID, [ECU-NAME]as ECUNAME FROM         TBL_ECU_MAST)
WHERE ECUID = 147;

请帮我解决这个问题。

4 个答案:

答案 0 :(得分:3)

只需给你的表达一个别名;

Select aliasHere.ECUID, aliasHere.ECUNAME 
FROM 
(SELECT     
    [ECU-ID] as ECUID, [ECU-NAME]as ECUNAME 
    FROM         TBL_ECU_MAST) aliasHere
WHERE aliasHere.ECUID = 147;

显然使用更具描述性的别名......

答案 1 :(得分:3)

您可以使用其他方式。例如下面的代码

;with t as
(
SELECT [ECU-ID] AS ECUID, [ECU-NAME] AS ECUNAME FROM TBL_ECU_MAST
)
SELECT ECUID,ECUNAME 
FROM t WHERE ECUID = 147

答案 2 :(得分:2)

正如@Gordon建议你必须为SQL语句中使用的SubQuery提供别名

SELECT ECUID,ECUNAME 
FROM 
  (SELECT [ECU-ID] AS ECUID, [ECU-NAME] AS ECUNAME FROM TBL_ECU_MAST) T
WHERE T.ECUID = 147;

希望这会有所帮助!!

答案 3 :(得分:0)

为所有子查询指定别名:

SELECT A.ECUID, A.ECUNAME 
FROM 
(
  SELECT [ECU-ID] as ECUID, [ECU-NAME]as ECUNAME 
  FROM TBL_ECU_MAST 
) A
 WHERE A.ECUID = 147;