在sqlserver中,需要选择两列之一,case语句可以做到这一点吗?

发布于 2024-08-10 03:25:39 字数 174 浏览 5 评论 0原文

我的表:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

在梵高的星空下 2024-08-17 03:25:39

使用 CASE:

SELECT t.userid,
       CASE
         WHEN [something to evaluate why to show col1 vs col2 ] THEN
           t.col1
         ELSE
           t.col2
       END
  FROM USERS t

使用 COALESCE:

SELECT t.userid,
       COALESCE(t.col1, t.col2)
  FROM USERS t

COALESCE 返回从左侧开始的第一个不为空的列值。

Using CASE:

SELECT t.userid,
       CASE
         WHEN [something to evaluate why to show col1 vs col2 ] THEN
           t.col1
         ELSE
           t.col2
       END
  FROM USERS t

Using COALESCE:

SELECT t.userid,
       COALESCE(t.col1, t.col2)
  FROM USERS t

COALESCE returns the first column value that isn't null, starting from the left.

我喜欢麦丽素 2024-08-17 03:25:39

是的,只要您不介意返回相同的列名:

SELECT userID, ArbitraryCol = CASE WHEN @param = 1 then col1 ELSE col2 END
FROM Users

如果您需要更改列标题,那么您应该使用 IF 语句

IF @param = 1
BEGIN
SELECT userID, col1 FROM Users
END
ELSE
BEGIN
SELECT userID, col2 FROM Users
END

Yes, as long as you don't mind returning the same column names:

SELECT userID, ArbitraryCol = CASE WHEN @param = 1 then col1 ELSE col2 END
FROM Users

If you need the column headers to change, then you should use the IF statement

IF @param = 1
BEGIN
SELECT userID, col1 FROM Users
END
ELSE
BEGIN
SELECT userID, col2 FROM Users
END
看轻我的陪伴 2024-08-17 03:25:39

我认为 SQL Server 2000/2005 就是这样的。

select
   UserID,
   case UserID
      when 1 then Col1
      when 2 then Col2
      else 'boo'
   end as SpecialSituation
from
   Users

I think SQL Server 2000/2005 is something like this.

select
   UserID,
   case UserID
      when 1 then Col1
      when 2 then Col2
      else 'boo'
   end as SpecialSituation
from
   Users
小…楫夜泊 2024-08-17 03:25:39

假设您有一个关于何时返回 col1 而不是 col2 的逻辑表达式,则可以:

SELECT USERID CASE WHEN USERTYPE='X' THEN COL1 ELSE COL2 END FROM USERS

如果 col1 和 col2 属于不同类型,则需要使用 CAST 或 CONVERT 将其中之一转换为另一种类型。

It can, assuming you have a logical expression for when to return col1 instead of col2:

SELECT USERID CASE WHEN USERTYPE='X' THEN COL1 ELSE COL2 END FROM USERS

If col1 and col2 are of different types, you will need to use CAST or CONVERT to convert one to the other.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文