简体   繁体   中英

SQL search script from CASE statement

Please help me with this.

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%'

I try to create simple search by text from database, so I can search by middle of the text. Because of there is no status column in there, I create it myself from combination of 2 column details. Can anyone help me. Thanks.

You can't use a alias directly in WHERE clause, try the below one

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%'

As an alternative, you could add your case expression on the WHERE clause.

Like

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

You can use HAVING keyword (works only in 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%'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM