简体   繁体   English

如何在SQL中为标识符设置别名

[英]How to set an alias for an identifier in SQL

Concept example: 概念示例:

declare @x varchar(max)

set @x = 'top 1 *'

select @x from table

Result wanted: 想要的结果:

For the script to function as: 为了使脚本起到以下作用:

select top 1 * from table

To return the first row in table. 返回表中的第一行。


Actual result: 实际结果:

The script functions as: 该脚本的功能如下:

select 'top 1 *' from table

Many rows return with values 'top 1 *' 许多行返回值“ top 1 *”


Use case: 用例:

In a more complex scenario, the x variable would be a much longer string that would need to be called upon several times later in the script. 在更复杂的情况下,x变量将是一个更长的字符串,需要在脚本中稍后多次调用。 Instead of pasting that long variable over and over, I want to set an alias for it. 我不想一遍又一遍地粘贴该长变量,而是要为其设置别名。 Is this possible? 这可能吗?

I think you want this: 我想你想要这个:

declare @x varchar(max), @sql varchar(max)

set @x = 'top 1 *'

set @sql = 'select '+ @x +' from table'

PRINT @sql;

--EXECUTE (@sql) -- Uncomment this when you are sure of your query

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

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