Mask SQL Select return

Asked

Viewed 342 times

2

I’m using the following SELECT to return the Ids one-table.

SELECT id, duracao_sessao FROM usuario
  • For ID 1 I want the text "Object"
  • For ID 2 I want the text "Class"
  • For ID 3 I want the text "Structure"

Is there any way to mask the return in a SELECT command in this way?

2 answers

3


According to the question, only a few Ids should be masked. If this is the goal, you can use the expression CASE. For example, in this way:

SELECT CASE
          WHEN ID = 1 THEN 'Objecto'
          WHEN ID = 2 THEN 'Classe'
          WHEN ID = 3 THEN 'Estrutura'
          ELSE CONVERT(VARCHAR, ID)
       END
  FROM usuario

The previous statement will return "Object", "Class" or "Structure" if the ID is 1, 2 or 3 respectively. For the remaining Ids, it will return the number itself. If you want to apply the exception for other Ids, simply include them in the list.

  • Thanks for the answer!! In fact, all ID should be masked, each with a different text understands? You could do it this way with 3 different texts?

  • There is no need to use the CASE statement. In the example I sent, the return is exactly the word text 1 for id user 1, text 10, id user 10... text 100 for id user 100... and so on.

  • Ta confused... what text you want for each user ?

  • I edited the question, I was really confused, I’m sorry... Now the question presents exactly the texts I need for each case and it’s only these 3 id types you have in the table

  • @dev-john, see updated response.

  • 1

    It worked @Runo Thank you so much!!!

  • You’re welcome, @dev-john

Show 2 more comments

1

Consider that syntax may vary according to DBMS. Here are some examples:

SELECT 'Texto' + cast(id as varchar(250)) FROM tabela (MS SQL SERVER)
SELECT 'Texto' || id FROM tabela (FIREBIRD)
SELECT CONCAT('Texto', id) AS campo from tabela (MYSQL)
  • I was able to do as follows: SELECT 'Text', duraca_sessao FROM dbo.usuario Where id = 1 select 'Text 2', duraca_sessao from dbo.usuario Where id = 2 select 'Text 3', duraca_sessao from dbo.usuario Where id = 3 But I need to do this filter in just one query. Do you know if it is possible? !!

  • Let me see if I got bored... You can put it in the IN.. Like this: SELECT 'Texto ' + cast(id as varchar(250)), duracao_sessao FROM dbo.usuario WHERE id IN (1,2,3);

  • Got it, only would he put the same text for the correct ID 1, 2 and 3? I need a different text for each ID

Browser other questions tagged

You are not signed in. Login or sign up in order to post.