不使用动态 SQL 的 T-SQL 动态别名 [英] T-SQL Dynamic alias without using dynamic SQL

查看:27
本文介绍了不使用动态 SQL 的 T-SQL 动态别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据场景命名列别名

I need the column alias to be named based on a scenario

declare @testing as varchar(max)
set @testing = 'choice'

select 1 as case when @testing = 'choice' then 'chose' else 'didntChoose' end

因此,如果@testing = 'choice',结果将如下所示:

So if @testing = 'choice', the results would look like this:

chose
1

其他:

didntChoose
1

是否可以在没有动态 SQL 的情况下做到这一点?

推荐答案

否,除非使用动态 SQL,否则不能根据值更改别名的名称.

No, you cannot change the name of the alias based on the value unless you use dynamic SQL.

选择列时,每一列只能有一个名称/别名.

When you are selecting the columns, you can only have one name/alias for each column.

如果您想要不同的列名,那么您可以使用以下使用不同选择语句的类似内容:

If you want different column names, then you could use some like the following which uses different select statements:

IF @testing = 'choice'
    select 1 as 'Chose'
ELSE 
    select 1 as 'didntChoose'   

或者您可以返回两个单独的列:

Or you could return two separate columns:

select 
    case when @testing = 'choice' then 1 else 0 end Chose,
    case when @testing <> 'choice' then 1 else 0 end DidNotChose

这篇关于不使用动态 SQL 的 T-SQL 动态别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆