在sqlserver中,需要选择两列之一,case语句可以做到这一点吗?
我的表:
Users (userID, col1, col2)
我想创建一个通用存储过程,但我需要在查询中返回 col1 或 col2。
我的案例陈述可以处理这种情况吗?
选择用户ID,列1 从用户
或
选择用户ID,col2 来自用户
My table:
Users (userID, col1, col2)
I want to make a generic stored procedure, but I need to return EITHER col1 or col2 in a query.
Can I case statement handle this situation?
SELECT userID, col1
FROM Users
OR
SELECT userID, col2
FROM Users
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 CASE:
使用 COALESCE:
COALESCE 返回从左侧开始的第一个不为空的列值。
Using CASE:
Using COALESCE:
COALESCE returns the first column value that isn't null, starting from the left.
是的,只要您不介意返回相同的列名:
如果您需要更改列标题,那么您应该使用 IF 语句
Yes, as long as you don't mind returning the same column names:
If you need the column headers to change, then you should use the IF statement
我认为 SQL Server 2000/2005 就是这样的。
I think SQL Server 2000/2005 is something like this.
假设您有一个关于何时返回 col1 而不是 col2 的逻辑表达式,则可以:
如果 col1 和 col2 属于不同类型,则需要使用 CAST 或 CONVERT 将其中之一转换为另一种类型。
It can, assuming you have a logical expression for when to return col1 instead of col2:
If col1 and col2 are of different types, you will need to use CAST or CONVERT to convert one to the other.