简体   繁体   English

where子句中的列别名给出了无效的列名错误

[英]Column aliases in where clause giving invalid column name error

This is a simple question that I'm hung up on. 这是一个简单的问题,我已经挂断了。 I want to know if I can create a column alias and then use it in my WHERE clause, ie: 我想知道我是否可以创建列别名然后在我的WHERE子句中使用它,即:

SELECT TRACTOR, CONVERT(VARCHAR, ORDER) AS NUMBER
FROM TABLE
WHERE NUMBER = '4'

Keep in mind this is just an example of what I'm trying to do. 请记住,这只是我想要做的一个例子。 The query I'm running is a bit more complex, but just the basic idea of how to create a variable and then use it in a clause. 我正在运行的查询有点复杂,但只是如何创建变量然后在子句中使用它的基本思路。

My question is about the aliased columns in the where clause. 我的问题是关于where子句中的别名列。 I have a query that looks for an invoice number in one database and matches it the first 7 digits of a field in another database. 我有一个查询在一个数据库中查找发票号,并将其与另一个数据库中字段的前7位数匹配。 The query worked fine when we only had 6 digits but now that we have 7, I'm getting an error and I'm trying to rewrite the query in a different manner. 当我们只有6位数时查询工作正常,但现在我们有7位,我收到错误,我试图以不同的方式重写查询。

Re-using aliased columns is a great use case for CROSS APPLY : 重复使用别名列是CROSS APPLY一个很好的用例:

SELECT t.TRACTOR, CxA.Num
FROM TABLE t
CROSS APPLY
  (SELECT CONVERT(VARCHAR(10), ORDER)) CxA(Num)
WHERE CxA.Num = '4'

Anything in a CROSS APPLY can be referenced in the SELECT , WHERE , ORDER BY , etc with some limitations (normally if you have aggregation in the CROSS APPLY expression). CROSS APPLY任何内容都可以在SELECTWHEREORDER BY等中引用,但有一些限制(通常如果您在CROSS APPLY表达式中有聚合)。

Take a look at: http://sqlmag.com/t-sql/working-variables-t-sql-part-1 请查看: http//sqlmag.com/t-sql/working-variables-t-sql-part-1

The basic syntax of variables would be like so: 变量的基本语法如下:

declare @id int
select @id = 1

select *
from myTable
where id = @id

EDIT: in case you're actually asking about column aliases in your where clause, and not sql variables, take a look at this SO question: Referring to a Column Alias in a WHERE Clause 编辑:如果您实际上询问where子句中的列别名,而不是sql变量,请查看此SO问题: 引用WHERE子句中的列别名

EDITx2: EDITx2:

for your specific case (assuming asking about column aliases) you could do the following: 对于您的特定情况(假设询问列别名),您可以执行以下操作:

SELECT *
FROM (
    SELECT TRACTOR, CONVERT(VARCHAR(100), ORDER) AS NUMBER
    FROM TABLE
) someTableAlias
WHERE NUMBER = '4'

Though you may want to rethink your column names... i think number and order are both reserved words, and should be avoided where possible. 虽然您可能想重新考虑您的列名...我认为数字和顺序都是保留字,应尽可能避免。 you can get around these for the most part by using [order] and [number] I believe, but still best to avoid reserved words as columns/tables/whatevers. 你可以通过使用[order]和[number]来解决这些问题,我相信,但最好还是避免使用保留字作为列/表/ whatevers。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM