来自CASE语句的SQL搜索脚本

时间:2017-03-02 08:11:24

标签: sql sql-server

请帮助我。

SELECT
   Username,
   CASE
      WHEN UserType = 'DUMMY' AND UserLoginId = Username THEN 'Awaiting_Approval'
      WHEN UserType = 'DUMMY' AND UserLoginId != Username THEN 'Checking_Approval'
      ELSE 'No_Status_Yet'
   END AS UserStatus
FROM MyTable
WHERE UserStatus LIKE '%king%'

我尝试通过数据库中的文本创建简单搜索,因此我可以在文本的中间进行搜索。由于那里没有状态列,我自己从2列详细信息的组合创建它。谁能帮我。感谢。

3 个答案:

答案 0 :(得分:4)

您不能在WHERE子句中直接使用别名,请尝试下面的

SELECT  *
FROM    (
    SELECT  Username,
           CASE
              WHEN UserType = 'DUMMY' AND UserLoginId = Username THEN 'Awaiting_Approval'
              WHEN UserType = 'DUMMY' AND UserLoginId != Username THEN 'Checking_Approval'
              ELSE 'No_Status_Yet'
           END AS UserStatus
    FROM MyTable
)   AS  D
WHERE UserStatus LIKE '%king%'

答案 1 :(得分:0)

作为替代方案,您可以在WHERE子句中添加案例表达式。

喜欢

SELECT
   Username,
   'Checking_Approval' AS UserStatus
FROM MyTable
WHERE 1 = CASE WHEN UserType = 'DUMMY' AND UserLoginId != Username THEN 1
          --other conditions that should be returned here
            ELSE 0
          END

答案 2 :(得分:-1)

您可以使用HAVING关键字(仅适用于MySQL):

SELECT
    Username,
    CASE
        WHEN UserType = 'DUMMY' AND UserLoginId = Username THEN 'Awaiting_Approval'
        WHEN UserType = 'DUMMY' AND UserLoginId != Username THEN 'Checking_Approval'
        ELSE 'No_Status_Yet'
        END AS UserStatus
FROM MyTable
HAVING UserStatus LIKE '%king%'