Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL Server: Assign to different Variables depending on the column value

I have a table user_config that stores code names and values.

For example, something like this:

id code value
sam ctr HK
sam curr HKD
sam altcurr EUR,USD
declare
    @country varchar(2),
    @currency varchar(3),
    @alternate_currencies varchar(100);

select @country = u.value
from user_config u
where u.code = 'ctr'
  and u.id = 'sam';

select @currency = u.value
from user_config u
where u.code = 'curr'
  and u.id = 'sam';

select @alternate_currencies = u.value
from user_config u
where u.code = 'altcurr'
  and u.id = 'sam';

Is there a way to assign variables in one SQL, depending on the value of code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The CASE statement will help you here

select @country = (case when u.code = 'ctr' then u.value else @country end),
       @currency = (case when u.code = 'curr' then u.value else @currency end),
       @alternate_currencies = (case when u.code = 'altcurr' then u.value else @alternate_currencies end)
  from user_config u
 where u.id = 'sam';

dbfiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading