如何获取全名作为别名并在 Like 语句中使用它

How to get a Full name as an Alias and use it in a Like statement

大家好,我是第一次来这样的论坛。我来自德国,所以英语不是我的母语所以请不要对我太苛刻:)。

Select top(1) firstname+' '+lastname AS APName 
From ansprech 
Where customernr = 10205 and APName LIKE '%Max Example';

我想使用我在这个 Like 语句中创建的别名。我搜索了将近一个小时,但找不到问题的正确答案,所以也许你们可以帮助我:)。

您可以使用subquery

SELECT * FROM 
(Select firstname+' '+lastname AS APName From ansprech Where customernr = 10205 ) TMP WHERE APName LIKE '%Max Example';

Select top(1) firstname+' '+lastname AS APName From ansprech Where (customernr = 10205) and ( firstname+' '+lastname LIKE '%Max Example');

在 SQL Server(和 Access)上,除了使用子查询或只是重复完整的别名表达式之外,您在这里没有太多选择。在这种情况下我会选择后者:

SELECT TOP(1)
    firstname + ' ' + lastname AS APName
FROM ansprech
WHERE customernr = 10205 AND firstname + ' ' + lastname LIKE '%Max Example';

SQL 当您 运行 一个 SELECT 查询时,服务器遵循以下处理顺序。Read more about Processing Order of SELECT query

Logical Processing Order of the SELECT statement

The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. The actual physical execution of the statement is determined by the query processor and the order may vary from this list.

  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  5. GROUP BY
  6. WITH CUBE or WITH ROLLUP
  7. HAVING
  8. SELECT
  9. DISTINCT
  10. ORDER BY
  11. TOP

您的别名将在 SELECT 阶段 8 中出现,因此不能在前面的阶段 4(WHERE 子句)中引用它。如果要在 WHERE 子句中引用别名,别名应该是 FROM 子句(第 1 阶段)的一部分,它位于 WHERE 子句(第 4 阶段)之前。您可以做的是,在 FROM 子句中有一个子查询以获取别名作为结果的一部分,然后在 WHERE 子句中使用它。

SELECT top(1) APName
FROM (SELECT firstname+' '+lastname AS APName, CustomerNr From ansprech) AS c 
WHERE customernr = 10205 and APName LIKE '%Max Example';

我更喜欢使用 APPLY 来模拟 类似变量的 行为:

USE master;

SELECT NewAlias
FROM [sys].[objects] o
CROSS APPLY(SELECT CONCAT(o.[name],' (',o.[object_id],')') AS NewAlias) A --A ist just an alias for the APPLY's result
WHERE NewAlias LIKE '%cols%';

APPLY 是一个按行 调用。如果引擎可以确定,这将 return 只是一行,这将执行闪电般的速度。您可以将其视为额外的 计算列 .

和 Shnugo 一样,我非常喜欢在 FROM 子句中定义标识符。对于您的查询,这看起来像:

select top(1) v.APName 
from ansprech a cross apply
     (values (a.firstname + ' ' + a.lastname)) v(APName)
where a.customernr = 10205 and
      v.APName like '%Max Example';