Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

Alter an Existing Column in SQL Server based on the contents of another existing column in the table

I am trying to alter the contents of an existing column in SQL Server based on the contents of another column in the same table. There is already some data in the column to be updated which I wish to retain if none of the cases described below apply.

So far I have pieced together the below statement but something if not many things are clearly being missed.

 Select 'Postal Code', 'Packaging Code',
 From [Clean Report]
     Alter Table [Clean Report]
        CASE 
            when [Postal Code, Clean Report] = '55419-4709'
                then [Packaging Code, Clean Report] = '079111123'
        Else
            when [Postal Code, Clean Report] = '80222'
                then [Packaging Code, Clean Report] = '809088899'
        Else (Leave what was already populated in 'Packaging Code, Clean Report Column'

So ideally I would end up with two hard coded values for the specific cases described above and then retain the data that was already populated in the [Packaging Code] Column where the cases above did not apply.

Any assistance is much appreciated!

question from:https://stackoverflow.com/questions/65599361/alter-an-existing-column-in-sql-server-based-on-the-contents-of-another-existing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you simply need to update two values, you could try the following query :

UPDATE [Clean Report]
  SET [Packaging Code] = '079111123'
WHERE
  [Postal Code] = '55419-4709';

UPDATE [Clean Report]
  SET [Packaging Code] = '809088899'
WHERE
  [Postal Code] = '80222';

You can check it on the following fiddle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...