在sql server 2012中使用别名

时间:2014-08-04 10:11:57

标签: sql sql-server-2012

首先让我提出我的代码:

SELECT   REPLACE(SUBSTRING(CreateDate,3,8),'/','') as registerdate, 
FROM     TatEstelam.dbo.tblInquiryRealForeigners RL 
         LEFT JOIN TatEstelam.dbo.CustomerInfo  CINFO
             ON RL.IdentificationDocumentNumber = CINFO.NationalID
WHERE-- NationalID <> '0001'
         IdentificationDocumentNumber <> ''
         AND registerdate BETWEEN '910404' AND '950505'

我的问题是我不能使用别名作为列。我的意思是,在最后一行,我想调用别名,但我不能。 例如,我想将此代码用于时间函数:

AND registerdate BETWEEN '910404' AND '950505'

3 个答案:

答案 0 :(得分:0)

正如你所说,你不能在where子句中使用别名 - 这是真的。 您应该使用整个表达式,如下所示。

SELECT   REPLACE(SUBSTRING(CreateDate,3,8),'/','') as registerdate, 
FROM TatEstelam.dbo.tblInquiryRealForeigners RL 
LEFT JOIN TatEstelam.dbo.CustomerInfo  CINFO
      ON RL.IdentificationDocumentNumber = CINFO.NationalID
WHERE-- NationalID <> '0001'
IdentificationDocumentNumber <> ''
AND REPLACE(SUBSTRING(CreateDate,3,8),'/','')  BETWEEN '910404' AND '950505'

答案 1 :(得分:0)

SELECT * FROM 
(
  SELECT   REPLACE(SUBSTRING(CreateDate,3,8),'/','') as registerdate, 
  FROM TatEstelam.dbo.tblInquiryRealForeigners RL LEFT JOIN TatEstelam.dbo.CustomerInfo  CINFO
  ON RL.IdentificationDocumentNumber = CINFO.NationalID
) AS registerdate 
WHERE-- NationalID <> '0001'
   IdentificationDocumentNumber <> ''
   AND registerdate BETWEEN '910404' AND '950505'

答案 2 :(得分:0)

您对日期有合理的表示,因此您只需更改常量:

SELECT   REPLACE(SUBSTRING(CreateDate, 3, 8), '/', '') as registerdate, 
FROM     TatEstelam.dbo.tblInquiryRealForeigners RL LEFT JOIN
         TatEstelam.dbo.CustomerInfo  CINFO
          ON RL.IdentificationDocumentNumber = CINFO.NationalID
WHERE    NationalID <> '0001' AND
         IdentificationDocumentNumber <> '' AND
         registerdate BETWEEN '1991/04/04' AND '1995/05/05';

这确实假设CreateDate的格式是一致的。这样做的另一个好处是它可以利用registerdate上的索引。

作为备注:不要将日期存储为字符串。 SQL Server对各种不同的日期类型都有很好的支持。将它们存储为日期,您不必处理转换问题。