微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SQL输出:是否可以创建临时输出列?

例如,我的数据库中有一个表格如下:

|物品编号|商品名称|价格|项目状态|

其中Item ID = int,Item Name = string,Price = int,Item Status = Enum

物品状态……
让我们说“2”代表“即将推出”,

“1”代表“可用”,

而“0”代表“已售完”

我想显示这样的信息,以便我可以告诉用户哪个视图输出表以更可接受的输出(字符串)知道状态,而不是查看Enum值:

| Item ID | Item Name | Price         | Item Status | **Description** |
| 123     | Apple     | [some number] | 0           |   Sold Out      |
| 234     | Orange    | [some number] | 2           |   Coming Soon   |

其中Description是我想要显示的临时列作为附加信息.

我可以知道一个GO语法是如何进行的吗?

请指导我.非常感谢你提前.

解决方法

那么最简单的方法是使用CASE语句 – 假设你只有3个描述?
select ItemId,Item_name,price,Item_status,Case
       When Item_status = 0 then 'Sold Out'
       When Item_status = 1 then 'Available'
       When Item_status = 2 then 'Coming Soon'
       End as [Description]

From dbo.YourTable

另一种选择,如果要创建一个临时表并加入到该表.

Create Table #TempEnums
(
Id int,Desc varchar(50)
)
Insert Into #TempEnums
Select 0,'Sold Out' Union Select 1,'Available' Union Select 2,'Coming Soon'

然后只需加入临时表即可

select a.ItemId,a.Item_name,a.price,a.Item_status,b.Desc as [Description]

From dbo.YourTable a
Join #TempEnums b on a.Item_Status = b.Id

编辑

要更改[description]列的数据类型,只需在Convert语句中进行换行

Convert(Varchar(25),Case
       When Item_status = 0 then 'Sold Out'
       When Item_status = 1 then 'Available'
       When Item_status = 2 then 'Coming Soon'
       End) as [Description]

原文地址:https://www.jb51.cc/mssql/74837.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐