简体   繁体   中英

SQL - assign variable with values from different columns based on value of column

I am new to SQL Server. My programming background is in SAS. I am currently using SQL Server Management Studio v18.5. I am trying to determine how to solve a couple of problems:

I want to assign new variables to existing columns, depending on the value of those columns. I have read about declaring variables using set and select, but I am having trouble translating that information to what I need to do. I have a view which contains several thousand records. I want the variable logic applied to each record in the view. The desired result is that I create a new view with just the new variable name and other associated data, excluding the original column names.

In SAS, my code would look like:

    If newctry<>' ' then countryname = newctry; 
                    else countryname = mailingcountry;

The existing columns are newctry and mailingcountry . The column newctry only has values when the mailingcountry value was invalid, otherwise the record value is blank.

I have different instances of this type of situation. Do I need to create subqueries for each of these instances? If someone could provide an example of how this might work in SQL, I would really appreciate it. An example of the SQL code I have tried is:

DECLARE @countryname VARCHAR(50)

SELECT recordid, recorddate, newctry, mailingcountry
FROM viewname

SELECT @countryname = newctry FROM viewname WHERE newctry <> ' ']
SELECT @countryname = mailingcountry FROM viewname WHERE newctry = ' '

The other question I have is that I have received errors when I have included multiple CASE statements with different END names in the Select statement. Do I need subqueries for each CASE statement?

Thanks!

I think you just want a case expression:

select (case when newctry <> ' ' then newctry else mailingcountry end) as countryname

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