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

How to set an alias for an identifier in SQL

概念示例:

declare @x varchar(max)

set @x = 'top 1 *'

select @x from table

想要的结果:

对于脚本的作用:

select top 1 * from table

至return第一行table。


实际结果:

脚本函数为:

select 'top 1 *' from table

许多行 return 的值为 'top 1 *'


用例:

在更复杂的情况下,x 变量将是一个更长的字符串,稍后需要在脚本中多次调用它。我不想一遍又一遍地粘贴那个长变量,而是想为它设置一个别名。这可能吗?

我想你想要这个:

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